No description, website, or topics provided.
JavaScript
Switch branches/tags
Nothing to show
Pull request Compare This branch is 1 commit ahead, 35 commits behind indexzero:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.gitignore
index.js
package.json
readme.markdown

readme.markdown

ps-tree

Summary

Sometimes you cannot kill child processes like you would expect; this a feature of UNIX.

in UNIX, a process may terminate by using the exit call, and its parent process may wait for that event by using the wait system call. The wait system call returns the process identifier of a terminated child, so that the parent tells which of the possibly many children has terminated. If the parent terminates, however, all its children have assigned the init process as their new parent. Thus, the children still have a parent to collect their status and execution statistics.
(from "Operating System Concepts")

Solution

Use ps-tree to get all processes that a child_process may have started, so that they may all be terminated.

var cp = require('child_process'),
  psTree = require('ps-tree');

var child = cp.exec("node -e 'while (true);'", function () {
	...
});

// this will not actually kill the child it will kill the `sh` process.
child.kill();

Why? It's because exec actually works like this:

function exec (cmd, cb) {
  spawn('sh', ['-c', cmd]);
  ...
}

sh starts parsing the command string, starts processes, and waits for them to terminate but exec returns a process object with the pid of the sh process.
Since it is in wait mode, killing it does not kill the children.

Use ps-tree like this:

var cp = require('child_process'),
  psTree = require('ps-tree');

var child = cp.exec("node -e 'while (true);'", function () {
  ...
});

psTree(child.pid, function (err, children) {
  cp.spawn(
    'kill',
    ['-9'].concat(children.map(function (p) {
      return p.PID;
    })
  ));
});