Skip to content

appendto/ps-tree

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%