gpt4 book ai didi

node.js - 捕捉 SIGTERM 与捕捉 SIGINT

转载 作者:IT老高 更新时间:2023-10-28 23:18:25 26 4
gpt4 key购买 nike

在 Node.js 服务器中,捕捉 SIGTERM 和捕捉 SIGINT 有什么区别吗?

我认为进程不应该能够防止在收到 SIGINT 时关闭?

  process.once('SIGINT', function (code) {
console.log('SIGINT received...');
server.close();
});

// vs.

process.once('SIGTERM', function (code) {
console.log('SIGTERM received...');
server.close();
});

我能否捕获两个信号并阻止退出?我的实验表明答案是肯定的,但根据我的阅读,SIGINT 总是假设关闭一个进程。

或者我把 SIGINT 和 SIGKILL 混淆了?也许 SIGKILL 是我无法恢复的信号?

捕获这些信号当然可以让我优雅地关机:

server.once('close', function(){
// do some other stuff
process.exit(2); // or whatever code pertains
});

我认为我将 SIGINT 与 SIGKILL 混淆了 -

如果我尝试这样做:

 process.once('SIGKILL', function (code) {
console.log('SIGKILL received...');
exitCode = code || 2;
server.close();
});

我收到此错误:

 internal/process.js:206
throw errnoException(err, 'uv_signal_start');
^
Error: uv_signal_start EINVAL
at exports._errnoException (util.js:1022:11)
at process.<anonymous> (internal/process.js:206:15)
at emitTwo (events.js:106:13)
at process.emit (events.js:191:7)
at _addListener (events.js:226:14)
at process.addListener (events.js:275:10)
at process.once (events.js:301:8)

所以显然你不能捕获 SIGKILL 信号,但你可以捕获 SIGINT 和 SIGTERM?

最佳答案

接受的答案主要集中在OP的问题

In Node.js servers, is there any difference between catching SIGTERM vs catching SIGINT? Am I able to trap both signals and prevent exit?

我来到这里是因为我想知道它们之间的区别。所以这里有更多的澄清。

  1. 来自 https://en.wikipedia.org/wiki/Unix_signal

SIGTERMThe SIGTERM signal is sent to a process to request its termination... SIGINT is nearly identical to SIGTERM.

  1. 关于命令kill的描述有点不清楚。

You can catch both of them and still be able to close the process with a SIGKILL - kill -9 pid

说得更清楚一点,就是不能trap SIGKILL 信号,但是可以trap SIGINT 和SIGTERM;即使两者都被程序捕获并被忽略,SIGKILL - kill -9 pid 仍然可以杀死它。

再次,从上面的维基:

The SIGKILL signal is sent to a process to cause it to terminate immediately (kill). In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal.

所以,总而言之,从上面的维基总结:

  • The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Ctrl+C.
  • The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate. SIGINT is nearly identical to SIGTERM.

所以关于“Catching SIGTERM vs catching SIGINT (in Node.js)”的标题,如果你想优雅地退出,比如处理Ctrl+C,trap SIGINT 单独使用就足够了,无需同时处理。在 Node.js 的范围之外,情况就不同了,请查看 Nicholas Pipitone 的评论。

关于node.js - 捕捉 SIGTERM 与捕捉 SIGINT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42450501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com