javascript 如何使用 pid 杀死 Node.js 子进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30052623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to kill Node.js child process using pid?
提问by FullStack
I am looking for a way to kill Node.js processes using their pid. I've been searching Google, StackOverflow, and the Node.js documentation for hours. It seems like something that should exist. I can only find how to do it based on my variable newProc
below, but I cannot do newProc.kill()
because I want to kill the child process from outside of the function scope. Additionally, I need to store something in MongoDB for record-keeping purposes, so I thought pid would be more appropriate.
我正在寻找一种使用 pid 杀死 Node.js 进程的方法。我已经在 Google、StackOverflow 和 Node.js 文档中搜索了几个小时。似乎是应该存在的东西。我只能根据newProc
下面的变量找到如何执行此操作,但我无法执行此操作,newProc.kill()
因为我想从函数范围之外终止子进程。此外,我需要在 MongoDB 中存储一些东西以进行记录保存,所以我认为 pid 会更合适。
var pid = newJob();
kill(pid); //<--anything like this?
var newJob = function () {
var exec = require('child_process').exec,
var newProc = exec("some long running job", function (error, stdout, stderr) {
console.log("stdout: " + stdout);
console.log("stderr: " + stderr);
if (error) console.log('exec error: ' + error);
});
return newProc.pid;
}
EDIT: Can I use process.kill(pid)
on a child process? The docsstate that it is a global object that can be accessed from anywhere.
编辑:我可以process.kill(pid)
在子进程上使用吗?该文件指出,这是可以从任何地方访问一个全局对象。
Finally, as a slight tangent, is there a way to ensure that the pid's will always be unique? I don't want to unintentionally kill a process, of course.
最后,稍微说一下,有没有办法确保 pid 始终是唯一的?当然,我不想无意中杀死一个进程。
回答by Denis Washington
process.kill()does the job. As said in your edit, process
is a global object available in every Node module.
process.kill()完成这项工作。正如您在编辑中所说,process
是每个 Node 模块中都可用的全局对象。
Note that the PID only uniquely identifies your child process as long as it is running. After it has exited, the PID might have been reused for a different process. If you want to be really sure that you don't kill another process by accident, you need some method of checking whether the process is actually the one you spawned. (newProc.kill()
is essentially a wrapper around process.kill(pid)
and thus has the same problem.)
请注意,PID 仅唯一标识您的子进程,只要它正在运行。退出后,PID 可能已被重新用于不同的进程。如果您想真正确定不会意外杀死另一个进程,则需要某种方法来检查该进程是否实际上是您生成的进程。(newProc.kill()
本质上是一个包装器process.kill(pid)
,因此有同样的问题。)