subprocess.kill([signal])


subprocess.kill() 方法向子进程发送信号。 如果没有给定参数,则进程将被发送 'SIGTERM' 信号。 有关可用信号的列表,请参阅 signal(7)。 如果 kill(2) 成功,则此函数返回 true,否则返回 false

const { spawn } = require('node:child_process');
const grep = spawn('grep', ['ssh']);

grep.on('close', (code, signal) => {
  console.log(
    `child process terminated due to receipt of signal ${signal}`);
});

// 发送 SIGHUP 到进程。
grep.kill('SIGHUP');

如果信号无法传达,则 ChildProcess 对象可能会触发 'error' 事件。 向已经退出的子进程发送信号不是错误,但可能会产生不可预见的结果。 具体来说,如果进程标识符 (PID) 已重新分配给另一个进程,则信号将传给该进程,而这可能会产生意外结果。

虽然该函数被称为 kill,但传给子进程的信号实际上可能不会终止该进程。

请参阅 kill(2) 以供参考。

在不存在 POSIX 信号的 Windows 上,signal 参数将被忽略,并且进程将被强制且突然地终止(类似于 'SIGKILL')。 有关更多详细信息,请参阅信号事件

在 Linux 上,子进程的子进程在试图杀死其父进程时不会被终止。 当在 shell 中运行新进程或使用 ChildProcessshell 选项时,可能会发生这种情况:

'use strict';
const { spawn } = require('node:child_process');

const subprocess = spawn(
  'sh',
  [
    '-c',
    `node -e "setInterval(() => {
      console.log(process.pid, 'is alive')
    }, 500);"`,
  ], {
    stdio: ['inherit', 'inherit', 'inherit'],
  },
);

setTimeout(() => {
  subprocess.kill(); // 不会终止 shell 中的 Node.js 进程。
}, 2000);

The subprocess.kill() method sends a signal to the child process. If no argument is given, the process will be sent the 'SIGTERM' signal. See signal(7) for a list of available signals. This function returns true if kill(2) succeeds, and false otherwise.

const { spawn } = require('node:child_process');
const grep = spawn('grep', ['ssh']);

grep.on('close', (code, signal) => {
  console.log(
    `child process terminated due to receipt of signal ${signal}`);
});

// Send SIGHUP to process.
grep.kill('SIGHUP');

The ChildProcess object may emit an 'error' event if the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences. Specifically, if the process identifier (PID) has been reassigned to another process, the signal will be delivered to that process instead which can have unexpected results.

While the function is called kill, the signal delivered to the child process may not actually terminate the process.

See kill(2) for reference.

On Windows, where POSIX signals do not exist, the signal argument will be ignored, and the process will be killed forcefully and abruptly (similar to 'SIGKILL'). See Signal Events for more details.

On Linux, child processes of child processes will not be terminated when attempting to kill their parent. This is likely to happen when running a new process in a shell or with the use of the shell option of ChildProcess:

'use strict';
const { spawn } = require('node:child_process');

const subprocess = spawn(
  'sh',
  [
    '-c',
    `node -e "setInterval(() => {
      console.log(process.pid, 'is alive')
    }, 500);"`,
  ], {
    stdio: ['inherit', 'inherit', 'inherit'],
  },
);

setTimeout(() => {
  subprocess.kill(); // Does not terminate the Node.js process in the shell.
}, 2000);