FullStack
FullStack

Reputation: 6020

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.

Upvotes: 15

Views: 30941

Answers (3)

Amit Kulkarni
Amit Kulkarni

Reputation: 81

use tree-kill module and pass the id as process.pid which kills the processes which are long and doesn't return.

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

exec("some long non-return job like server start", function (error, stdout, stderr) {
console.log("stdout: " + stdout);
console.log("stderr: " + stderr);
if (error) console.log('exec error: ' + error);
});       
kill(process.pid);

Upvotes: 0

Manute
Manute

Reputation: 103

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

Upvotes: 4

Denis Washington
Denis Washington

Reputation: 5672

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

Upvotes: 20

Related Questions