捕获 SIGTERM 与捕获 SIGINT

Catching SIGTERM vs catching SIGINT

在 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?

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

SIGINT 由用户按 Ctrl+C 生成,是一个 interrupt

SIGTERM 是发送以请求进程终止的信号。 kill 命令发送一个 SIGTERM 并且它是一个 terminate

您可以捕获 SIGTERMSIGINT 并且您将始终能够使用 SIGKILLkill -9 [pid].

关闭进程

接受的答案主要集中在 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

SIGTERM The 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

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

同样,来自上面的 wiki:

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.

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

  • 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 ,单独捕获 SIGINT 就足够了,不需要同时处理两者。在 Node.js 的范围之外,这是一个不同的故事,查看 Nicholas Pipitone 的评论。