最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node子进程:如何拦截像SIGINT这样的信号

网站源码admin47浏览0评论

Node子进程:如何拦截像SIGINT这样的信号

Node子进程:如何拦截像SIGINT这样的信号

在我的 Node 应用程序中,我正在连接

SIGINT
信号以优雅地停止(使用
pm2
,但这与此处无关)。

我的应用程序还执行/生成几个子进程。

我能够钩住

SIGINT
拦截它并执行优雅停止,但是我的子进程通过相同的信号传递,因此立即被杀死。

如何拦截子进程上的

SIGINT
信号?

我正在做的一个例子:

const child = child_process.spawn('sleep', ['10000000']);
console.log(`Child pid: ${child.pid}`);

child.on('exit', (code, signal) => { console.log('Exit', code, signal); });

process.on('SIGINT', () => {
    console.log("Intercepting SIGINT");
});
回答如下:

默认情况下,由

child_process.spawn()
创建的子进程与父进程具有相同的 进程组,除非使用
{detached:true}
选项调用它们。

结果是这个脚本在不同的环境下会有不同的表现:

// spawn-test.js
const { spawn } = require('child_process');
const one = spawn('sleep', ['101']);
const two = spawn('sleep', ['102'], {detached: true});
two.unref();
process.on('SIGINT', function () {
  console.log('just ignore SIGINT');
});

在交互式 shell 上,默认情况下,来自 Ctl-C 的 SIGINT 会发送到整个组,因此未分离的孩子将获得 SIGINT 并退出:

you@bash $ node spawn-test.js
^Cjust ignore SIGINT
# the parent process continues here, let's check children in another window:
you@bash [another-terminal-window] $ ps aux | grep sleep
... sleep 102
# note that sleep 101 is not running anymore
# because it recieved the SIGINT from the Ctl-C on parent

...但是调用

kill(2)
可以只向您的父进程发出信号,所以孩子们还活着:

you@bash $ node spawn-test.js & echo $?
[2] 1234
you@bash [another-terminal-window] $ kill -SIGINT 1234
you@bash [another-terminal-window] $ ps aux | grep sleep
... sleep 101
... sleep 102
# both are still running

但是,pm2 完全是另一种野兽。即使您尝试上述技术,它也会杀死整个进程树,包括您的分离进程,即使有很长的

--kill-timeout

# Test pm2 stop
you@bash $ pm2 start spawn-test.js --kill-timeout 3600
you@bash $ pm2 stop spawn-test
you@bash $ ps aux | grep sleep
# both are dead

# Test pm3 reload
you@bash $ pm2 start spawn-test.js --kill-timeout 3600
you@bash $ pm2 reload spawn-test
you@bash $ ps aux | grep sleep
# both have different PIDs and were therefore killed and restarted

这似乎是 pm2 中的一个错误。

我通过使用 init 系统(在我的例子中是 systemd)而不是 pm2 解决了类似的问题,因为这允许更好地控制信号处理。

在 systemd 上,信号默认发送到整个组,但您可以使用

KillMode=mixed
将信号仅发送到父进程,但如果子进程运行超过超时时间,它们仍然 SIGKILL。

我的 systemd 单元文件如下所示:

[Unit]
Description=node server with long-running children example

[Service]
Type=simple
Restart=always
RestartSec=30
TimeoutStopSec=3600
KillMode=mixed
ExecStart=/usr/local/bin/node /path/to/your/server.js

[Install]
WantedBy=multi-user.target
发布评论

评论列表(0)

  1. 暂无评论