我在端口 5100 上运行一个 Node 服务器。它执行一个 shell 脚本作为子进程,然后启动另一个 Node 服务器。
var execFile = require('child_process').execFile;
execFile("./testscript", args, {cwd: cwd}, function (error, stdout, stderr) {
console.log("error.." + error);
console.log("stdout.." + stdout);
console.log("stderr.." + stderr);
})
在脚本中,我通过 nohup 运行一个 Node 进程:
nohup node server.js PORT=5200 2>/dev/null 1>/dev/null &
现在 node@5200 有 testscript 的 parentid,而 testscript 又有 node@5100 的 parentid。 当我杀死 node@5100 的 PID 时,一切都停止了。
我希望 node@5200 在 testscript 和 node@5100 退出时仍然运行。
最佳答案
创建子进程时需要设置detached
选项。这有点像 nohup
。请参阅此处的文档:http://nodejs.org/api/child_process.html#child_process_options_detached
这样做的目的是让子进程成为新“进程组”的领导者,这样当父进程组死亡时,子进程可以继续运行。
编辑:文档说:
When using the detached option to start a long-running process, the process will not stay running in the background 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.
所以你必须这样写代码:
var child = spawn(cmd, args, {detached: true, stdio: ['ignore', 'ignore', 'ignore']});
child.unref();
或者您可以使用他们的示例将标准输出重定向到文件等。
关于node.js - 从作为子进程运行的脚本将 Node 作为后台进程运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27632354/