11

根据文档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();

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

node handoff-exec.js
hello
echo $?
0

那么......是否有可能在 node.js 中(或根本)在父级退出时在前台运行一个子级?

错误节点版本

我发现删除console.log('hello');允许孩子运行,但是,它仍然没有将前台标准输入控制传递给孩子。这显然不是故意的,因此我当时使用的节点版本肯定有问题......

https://github.com/nodejs/node/issues/5549

4

2 回答 2

0

解决方案

问题中的代码实际上是正确的。当时节点中有一个合法的错误。

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

上面的代码片段将有效地运行,就好像它已被 shell 作为后台一样:

ping -c 3 google.com &
于 2019-08-16T17:16:38.827 回答
-2

你不见了

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

于 2017-07-27T02:45:29.190 回答