node.js - 从作为子进程运行的脚本将 Node 作为后台进程运行

标签 node.js bash shell child-process

我在端口 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/

相关文章:

从 shell 启动的仪器的 iPhone(硬件?)id

java - 是否可以在 Spring Shell 中对值进行制表符补全?

node.js - 如何在 nodeJs 服务器上正确使用 Forest Admin? (与森林 express Mongoose )

bash - 递归 wget 不起作用

regex - 在 bash 中批量文件重命名,删除带空格的名称,留下尾随数字

bash - Presto 查询的简单批处理脚本

linux - 在 bash 脚本中执行多个命令

windows - NPM 已停止在 Windows 7 64 位上工作,在安装/更新时挂起

java - 通过 HTTP 从 android 应用程序发送到 nodejs 服务器后,我的 JSON 看起来不同

node.js - KOA响应错误水线