Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill Node.js child process using pid?

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.

like image 885
FullStack Avatar asked May 05 '15 12:05

FullStack


2 Answers

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

like image 111
Denis Washington Avatar answered Oct 11 '22 06:10

Denis Washington


You can use the module "tree-kill".

var kill  = require('tree-kill');
var exec  = require('child_process').exec;

  var child = exec('program.exe',  {cwd: 'C:/test'}, (err, stdout, stderr) => {
        if (stdout) console.log('stdout: ' + stdout);
        if (stderr) console.log('stderr: ' + stderr);
        if (err !== null) {
          console.log('exec error: ' + err)};
    });
  child.stdout.on('data', function(log_data) {
      console.log(log_data)
  });

kill(child.pid);

This kill you child process by it PID for sure ;-)

like image 3
Manute Avatar answered Oct 11 '22 04:10

Manute