2016-03-03 32 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