node.js:如何在前臺生成分離的子節點並退出

根據 the docs

for child_process.spawn,我希望能夠在前臺執行子程序並允許節點程序本身退出,如下所示:

切換-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(或根本沒有)可以在父節點退出時在前臺執行子節點嗎?

更新:我發現刪除console.log(‘hello’);允許孩子跑,但是,它仍然沒有將前臺標準控制傳遞給孩子.

你錯過了

// 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();

翻譯自:https://stackoverflow.com/questions/35767918/node-js-how-to-spawn-detached-child-in-foreground-and-exit