2016-03-03 35 views
8

根据the docschild_process.spawn我希望能够在前台运行一个子进程,并允许节点过程本身退出,像这样:的node.js:如何产卵沾边儿的前景和出口

handoff-exec.js

'use strict'; 

var spawn = require('child_process').spawn; 

// this console.log before the spawn seems to cause 
// the child to exit immediately, but putting it 
// afterwards seems to not affect it. 
//console.log('hello'); 

var child = spawn(
    'ping' 
, [ '-c', '3', 'google.com' ] 
, { detached: true, stdio: 'inherit' } 
); 

child.unref(); 

看到ping命令的输出代替,它简单地退出而没有任何消息或错误。

node handoff-exec.js 
hello 
echo $? 
0 

所以......有没有可能在node.js中(或全部)在前台作为父退出运行一个孩子?

UPDATE:我发现删除console.log('hello');允许孩子运行,但是,它仍然不会将前台stdin控制权交给孩子。

+0

可能的重复[我如何侦听和产生多个子进程在nodejs](http://stackoverflow.com/questions/32358845/how-do-i-listen-and-spawn-multiple-child-process- in-nodejs) –

+0

没有。这是关于在JavaScript中使用闭包来捕获对多个子进程的JS引用。这是关于过程参考,并让孩子掌握标准输入。 – CoolAJ86

+0

对于它的价值,我试着运行你的代码,它按照我的预期工作 - 节点进程退出,ping命令输出打印到stdout。这是在Mac OS和node.js v5.4.1上。如果我取消注释console.log - 我觉得很奇怪,它不起作用。 –

回答

-1

你缺少

// Listen for any response: 
child.stdout.on('data', function (data) { 
    console.log(data.toString()); 
}); 

// Listen for any errors: 
child.stderr.on('data', function (data) { 
    console.log(data.toString()); 
}); 

,你不需要child.unref();

+1

这会导致父进程继续运行。 – CoolAJ86