Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  67] [ 1]  / answers: 1 / hits: 27180  / 9 Years ago, tue, may 5, 2015, 12:00:00

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.



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 docs state that it is a global object that can be accessed from anywhere.



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.


More From » node.js

 Answers
99

process.kill() does the job. As said in your edit, process is a global object available in every Node module.



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.)


[#66735] Monday, May 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycie

Total Points: 414
Total Questions: 96
Total Answers: 117

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
;