信号事件


【Signal events】

当 Node.js 进程收到信号时,将会发出信号事件。请参阅 signal(7) 以查看标准 POSIX 信号名称的列表,例如 'SIGINT''SIGHUP' 等。

【Signal events will be emitted when the Node.js process receives a signal. Please refer to signal(7) for a listing of standard POSIX signal names such as 'SIGINT', 'SIGHUP', etc.】

Worker 线程上没有信号。

【Signals are not available on Worker threads.】

信号处理程序将接收信号的名称(如 'SIGINT''SIGTERM' 等)作为第一个参数。

【The signal handler will receive the signal's name ('SIGINT', 'SIGTERM', etc.) as the first argument.】

每个事件的名称将是信号的常用大写名称(例如,SIGINT 信号对应 'SIGINT')。

【The name of each event will be the uppercase common name for the signal (e.g. 'SIGINT' for SIGINT signals).】

import process from 'node:process';

// Begin reading from stdin so the process does not exit.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// Using a single function to handle multiple signals
function handle(signal) {
  console.log(`Received ${signal}`);
}

process.on('SIGINT', handle);
process.on('SIGTERM', handle);const process = require('node:process');

// Begin reading from stdin so the process does not exit.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// Using a single function to handle multiple signals
function handle(signal) {
  console.log(`Received ${signal}`);
}

process.on('SIGINT', handle);
process.on('SIGTERM', handle);
  • 'SIGUSR1' 被 Node.js 保留用来启动 调试器。可以安装一个监听器,但这样做可能会干扰调试器。
  • 'SIGTERM''SIGINT' 在非 Windows 平台上有默认处理程序,它们会在退出时以代码 128 + 信号编号 重置终端模式。如果给其中一个信号安装了监听器,其默认行为将被移除(Node.js 将不再退出)。
  • 默认情况下会忽略 'SIGPIPE'。可以为其安装监听器。
  • 在 Windows 上,当控制台窗口关闭时会生成 'SIGHUP',在其他平台下也会在各种类似情况下生成。请参见 signal(7)。可以安装监听器,但是 Windows 会在大约 10 秒后无条件终止 Node.js。在非 Windows 平台上,SIGHUP 的默认行为是终止 Node.js,但一旦安装了监听器,其默认行为将被移除。
  • 'SIGTERM' 在 Windows 上不受支持,但可以监听它。
  • 来自终端的 'SIGINT' 在所有平台上都受支持,通常可以通过 Ctrl+C 生成(尽管这可能是可配置的)。当启用 终端原始模式 并使用 Ctrl+C 时,它不会被生成。
  • 'SIGBREAK' 在 Windows 上会在按下 Ctrl+Break 时触发。在非 Windows 平台上,可以监听它,但没有办法发送或生成它。
  • 'SIGWINCH' 会在控制台尺寸改变时发送。在 Windows 上,这只会在控制台写入时发生,前提是光标正在移动,或者在使用原始模式的可读 tty 时发生。
  • 'SIGKILL' 无法安装监听器,它将在所有平台上无条件终止 Node.js。
  • 'SIGSTOP' 不能安装监听器。
  • 'SIGBUS''SIGFPE''SIGSEGV''SIGILL',当不是通过 kill(2) 人为触发时,本质上会使进程处于一个不安全的状态,此时调用 JS 监听器是不安全的。这样做可能会导致进程停止响应。
  • 0 可以用于测试进程是否存在,如果进程存在则不会有任何作用,但如果进程不存在则会抛出错误。

Windows 不支持信号,因此没有与信号终止相对应的功能,但 Node.js 提供了一些通过 process.kill() 的模拟,以及 subprocess.kill()

【Windows does not support signals so has no equivalent to termination by signal, but Node.js offers some emulation with process.kill(), and subprocess.kill():】

  • 发送 SIGINTSIGTERMSIGKILL 会导致目标进程被无条件终止,之后,subprocess 将报告该进程已被信号终止。
  • 发送信号 0 可作为一种平台无关的方法来测试进程是否存在。