我在 Windows (Win 10 64x) 上遇到了同样的问题。我无法终止生成的子进程的进程。
我使用child_process.spawn()启动一个服务(自定义HTTP服务器service.windows):
const { spawn } = require('child_process');
let cp = spawn('"C:\\Users\\user\\app\\service.windows"', [], { shell: true, });
cp.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
console.log('cp.connected', cp.connected);
console.log('process.pid', process.pid); // 6632 <<= main node.js PID
console.log('cp.pid', cp.pid); // 9424 <<= child PID
// All these are useless, they just kill `cp`
cp.kill('SIGINT'); // Doesn't terminate service.windows
cp.kill('SIGKILL'); // Doesn't terminate service.windows
cp.kill('SIGTERM'); // Doesn't terminate service.windows
});
我想终止我的 HTTP 服务器服务 (service.windows)。在 Windows 上使用 cp.kill('ANY SIGNAL') 是不可能的。 Node.js 杀死了它的子进程 (cp) 但我的 HTTP 服务器 (service.windows) 仍然运行良好。
当我在其他终端查看时,我发现我的服务器运行良好:
$ netstat -ano | findstr :9090
TCP 0.0.0.0:9090 0.0.0.0:0 LISTENING 1340
TCP [::]:9090 [::]:0 LISTENING 1340
我尝试通过PID 手动杀死我的服务器,但使用T 标志,而不是F。区别:
T连同父进程一起终止所有子进程,俗称树杀。
F 进程被强制终止。
$ taskkill -T -PID 1340
ERROR: The process with PID 1340 (child process of PID 9424) could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).
它准确地说我的服务器 1340 是 cp 的子服务器 - PID 9424。
好的,我尝试再次使用T 标志终止cp。和繁荣,不可能。 cp 是我的主要 node.js 的一个孩子 process.pid 6632:
$ taskkill -T -PID 9424
ERROR: The process with PID 1340 (child process of PID 9424) could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).
ERROR: The process with PID 9424 (child process of PID 6632) could not be terminated.
Reason: One or more child processes of this process were still running.
我只能用F标志强行杀死它:
$ taskkill -F -T -PID 9424
SUCCESS: The process with PID 1340 (child process of PID 9424) has been terminated.
SUCCESS: The process with PID 9424 (child process of PID 6632) has been terminated.
最令人失望的是,Node.js 文档没有说明如何处理这个问题。他们只会说“是的,我们知道存在问题,我们只是通知您”。
我在 Windows 上看到的唯一选项是在衍生进程中使用 taskkill -F -T -PID 9424:
exec('taskkill -F -T -PID 9424');