【问题标题】:node.js: How to spawn detached child in foreground and exitnode.js:如何在前台生成分离的孩子并退出
【发布时间】:2016-06-16 12:39:50
【问题描述】:

根据the docs for 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

【问题讨论】:

  • 不。那是关于在 JavaScript 中使用闭包来捕获对多个子进程的 JS 引用。这是关于进程引用和让孩子控制标准输入。
  • 对于它的价值,我尝试运行您的代码,它按预期工作 - 节点进程退出,并且 ping 命令输出被打印到标准输出。这是在 Mac OS 和 node.js v5.4.1 上。如果我取消对 console.log 的注释,它就不起作用——我觉得这很奇怪。

标签: node.js process child-process detach background-foreground


【解决方案1】:

解决方案

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

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

上面的 sn-p 将像在 shell 后台运行一样有效地运行:

ping -c 3 google.com &

【讨论】:

    【解决方案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();

    【讨论】:

    • 这会导致父进程继续运行。
    猜你喜欢
    • 2013-11-04
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    相关资源
    最近更新 更多