Coo*_*J86 10 process detach child-process background-foreground node.js
根据文档,child_process.spawn
我希望能够在前台运行子进程,并允许节点进程本身退出,如下所示:
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();
Run Code Online (Sandbox Code Playgroud)
ping
它只是退出而没有任何消息或错误,而不是看到命令的输出.
node handoff-exec.js
hello
echo $?
0
Run Code Online (Sandbox Code Playgroud)
所以......在node.js(或根本没有)可以在父节点退出时在前台运行子节点吗?
更新:我发现删除console.log('hello');
允许孩子运行,但是,它仍然没有将前台标准输入控制传递给孩子.
问题中的代码实际上是正确的。当时节点中存在一个合法的错误。
'use strict';
var spawn = require('child_process').spawn;
console.log("Node says hello. Let's see what ping has to say...");
var child = spawn(
'ping'
, [ '-c', '3', 'google.com' ]
, { detached: true, stdio: 'inherit' }
);
child.unref();
Run Code Online (Sandbox Code Playgroud)
上面的代码片段将有效地运行,就像它在 shell 的后台运行一样:
ping -c 3 google.com &
Run Code Online (Sandbox Code Playgroud)