我对此感到非常困惑,并且几个月来一直在努力寻找解决方案。我在 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真正创建一个独立于父进程的后台进程?这简直要了我的命!
最佳答案
啊哈!当然。那些愚蠢的 Node 文档!
这有效。
const n = cp.spawn('node', ['lib/transpile/watch-transpile.js'], {
detached: true,
stdio: ['ignore', 'ignore', 'ignore']
});
您显式忽略每个 stdio 流,而不仅仅是使用“忽略”一次;文档没有直接提到这一点,但考虑到 stdio 属性是一个数组,这是有道理的。
在 Github 上查看此问题:https://github.com/nodejs/node/issues/7269#issuecomment-225698625
关于node.js - 即使 detached 设置为 true,父进程也会杀死子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427360/