2014-07-22 36 views
0

我正在写一个实用程序。此实用程序的一个命令是运行一个外部应用程序。NodeJS:退出父母,让孩子活着

var child_process = require('child_process'); 
var fs = require('fs'); 

var out = fs.openSync('.../../log/out.log', 'a'); 
var err = fs.openSync('.../../log/err.log', 'a'); 

exports.Unref = function(app, argv) { 

    var child = child_process.spawn(app, argv, { 
    detached: true, 
    stdio: [ 'ignore', out, err ] 
    }); 
    child.unref(); 
    //process.exit(0); 
}; 

目前:

$ utility run app --some-args // run external app 
    // cant enter next command while app is running 

我的问题是,如果我运行此命令,“外部”应用程序运行时,终端将被锁定。

但是终端窗口不应该被child_process锁定。

我想运行:

$ utility run app --some-args 
$ next-command 
$ next-command 

外部应用程序(桌面应用程序)将hisself关闭。

像这样:

$ subl server.js // this runs Sublime Text and passes a file to the editor 
$ npm start // The terminal does not locked - i can execute next command while Sublime is still running 

你知道我的意思^^?

+0

您是否尝试追加类似'['>> ../../log/out.log','2 >> ../../log/err.log']'到' argv'而不是将两个文件打开?这很可能是保持流程开放的原因。 – mscdex

+0

嘿谢谢。这样可行。我明白,但有一件事我不明白。为什么我给它产生这个流参数,如果他不能分离这个过程....? – Nax

回答

0

['>>../../log/out.log', '2>>../../log/err.log']添加到argv的末尾而不是保留两个文件打开应该工作,因为它是保持进程活着的打开文件句柄。

传递stdio打开文件描述符除了detached: true因为没有办法unref()在父进程的文件描述符将无法正常工作,你所期望的方式,并有它仍然为子进程的工作。即使有办法,我相信当父进程退出时,操作系统会清理(关闭)它打开的文件描述符,这会导致分离的子进程出现问题。

这可能已经能够工作的唯一可能的方式是将文件描述符传递给子进程,但该功能在几个稳定的分支之前被丢弃,因为其他平台上不存在相同的功能(参见:视窗)。