父进程杀死子进程,即使 detached 设置为 true

parent process kills child process, even though detached is set to true

我真的很困惑,几个月来一直在努力寻找解决方案。我在 OSX.

我听说使用 child_process.spawn 并将 detached 选项设置为 true,将启动子进程作为新进程组的领导者,如果父进程退出,子进程可能会继续 运行宁。但是,我从未见过任何证据。

https://nodejs.org/api/child_process.html

例如:

const n = cp.spawn('node', ['watch-transpile.js'], {
    detached: true,
    stdio: ['ignore']
});

上面是父级执行的,如果我们运行$ ps aux | grep node

我们得到:

Olegzandr        2546   0.0  0.2  3048544  19564   ??  Ss   11:29PM   0:00.09 node lib/transpile/watch-transpile.js

Olegzandr        2541   0.0  0.7  3115684  60216 s000  S+   11:29PM   0:01.47 node index -t -a -w

但是当我用 control-c 杀死父进程时,子进程和父进程一起死掉。

如何用node创建一个真正独立于父进程的后台进程?这简直要了我的命!

尝试包括 child.unref() 方法。

By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given child, use the child.unref() method. Doing so will cause the parent's event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and parent.

When using the detached option to start a long-running process, the process will not stay running in the background after the parent exits unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

Example of a long-running process, by detaching and also ignoring its parent stdio file descriptors, in order to ignore the parent's termination:

示例:

const n = cp.spawn('node', ['watch-transpile.js'], {
    detached: true,
    stdio: ['ignore']
}).unref();

示例来自文档):

const spawn = require('child_process').spawn;

const child = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: ['ignore']
});

child.unref();

或者,可以将子进程的输出重定向到文件中:

const fs = require('fs');
const spawn = require('child_process').spawn;
const out = fs.openSync('./out.log', 'a');
const err = fs.openSync('./out.log', 'a');

const child = spawn('prg', [], {
 detached: true,
 stdio: [ 'ignore', out, err ]
});

child.unref();

啊哈!当然。那些愚蠢的 Node 文档!

这有效。

        const n = cp.spawn('node', ['lib/transpile/watch-transpile.js'], {
            detached: true,
            stdio: ['ignore', 'ignore', 'ignore']
        });

您明确地忽略了每个 stdio 流,而不仅仅是使用 'ignore' 一次;文档没有直接提到这一点,但考虑到 stdio 属性 是一个数组,这是有道理的。

在 Github 上查看此问题:https://github.com/nodejs/node/issues/7269#issuecomment-225698625