node.js:如何在前景中产生分离的子节点并退出

根据child_process.spawn 的文档 ,我期望能够在前台运行一个subprocess,并允许节点进程自己退出,如下所示:

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(或者全部)在父节点退出时在前台运行一个子节点?

更新 :我发现删除console.log('hello'); 允许孩子跑,但是,它仍然不会将前景stdin控制传递给孩子。

你错过了

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