简体   繁体   English

杀死CPU绑定的子进程

[英]Killing CPU bound child process

I have a child process spawned using child_process.fork and would like to terminate it. 我有一个使用child_process.fork生成的子进程,想终止它。 The problem is that the child process does some lengthy CPU bound calculation and I don't have control over it. 问题是子进程会执行一些冗长的CPU限制计算,而我无法控制它。 That is, the CPU bound code fragment cannot be restructured to make use of process.nextTick or polling. 即,CPU绑定的代码片段无法重组以使用process.nextTick或轮询。

A very simplified example: 一个非常简化的示例:

parent.js parent.js

var cp = require('child_process');
var child = cp.fork('child.js');

child.js child.js

...
while(true){} // lengthy computation which I cannot modify
...

Is it possible to terminate it? 是否可以终止? Preferably in a way that allows catching the exit event in the child in order to do some cleanups? 最好以某种方式允许捕获孩子中的退出事件以进行一些清理?

Sending SIGTERM/SIGKILL/etc using child.kill() doesn't seem to work on Windows. 使用child.kill()发送SIGTERM / SIGKILL / etc在Windows上似乎不起作用。 I assume even if it works on other OSes it wouldn't kill the process anyway due to child not being able to process events while doing the computation. 我假设即使它在其他OS上也能正常工作,因为孩子在执行计算时无法处理事件,因此无论如何也不会终止该过程。

I've done this the messy way by using the PID of the process and killing it at the OS level. 我通过使用进程的PID并在OS级别将其杀死来以一种凌乱的方式完成此任务。

Not sure how to do it in windows, but in Linux/mac I've done: 不确定如何在Windows中执行此操作,但是在Linux / mac中,我已经完成了:

var cp      = require('child_process'),
    badJob  = cp.fork('badFile.js');

cp.execSync('kill -9 ' + badJob.pid);

The signal 9 is caught at the Kernel level , so the condition of the process is irrelevant. 信号9是在内核级别捕获的 ,因此处理的条件无关紧要。

Edit: In Windows you can use taskkill instead of kill. 编辑:在Windows中,您可以使用taskkill而不是kill。 ex: 例如:

cp.execSync('taskkill /f ' + badJob.pid);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM