Skip to content

Commit

Permalink
Merge pull request #2 from remy/feat/remove-ps-tree
Browse files Browse the repository at this point in the history
fix: remove pstree
  • Loading branch information
remy authored Nov 22, 2018
2 parents 1da0189 + d12ab4f commit 6d8ac2b
Show file tree
Hide file tree
Showing 4 changed files with 535 additions and 504 deletions.
4 changes: 2 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const exec = require('child_process').exec;
const psTree = require('ps-tree');
const tree = require('./tree');
const utils = require('./utils');
var hasPS = true;

Expand All @@ -14,7 +14,7 @@ module.exports = function main(pid, callback) {
}

if (hasPS && !process.env.NO_PS) {
return psTree(pid, callback);
return tree(pid, callback);
}

utils
Expand Down
95 changes: 95 additions & 0 deletions lib/tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
'use strict';

var childProcess = require('child_process');
var spawn = childProcess.spawn;
var exec = childProcess.exec;

module.exports = function(pid, signal, callback) {
var tree = {};
var pidsToProcess = {};
tree[pid] = [];
pidsToProcess[pid] = 1;

if (typeof signal === 'function' && callback === undefined) {
callback = signal;
signal = undefined;
}

switch (process.platform) {
case 'darwin':
buildProcessTree(
pid,
tree,
pidsToProcess,
function(parentPid) {
return spawn('pgrep', ['-P', parentPid]);
},
function() {
callback(Object.keys(tree));
}
);
break;
// case 'sunos':
// buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
// killAll(tree, signal, callback);
// });
// break;
default:
// Linux
buildProcessTree(
pid,
tree,
pidsToProcess,
function(parentPid) {
return spawn('ps', [
'-o',
'pid',
'--no-headers',
'--ppid',
parentPid,
]);
},
function() {
callback(Object.keys(tree));
}
);
break;
}
};

function buildProcessTree(
parentPid,
tree,
pidsToProcess,
spawnChildProcessesList,
cb
) {
var ps = spawnChildProcessesList(parentPid);
var allData = '';
ps.stdout.on('data', function(data) {
var data = data.toString('ascii');
allData += data;
});

var onClose = function(code) {
delete pidsToProcess[parentPid];

if (code != 0) {
// no more parent processes
if (Object.keys(pidsToProcess).length == 0) {
cb();
}
return;
}

allData.match(/\d+/g).forEach(function(pid) {
pid = parseInt(pid, 10);
tree[parentPid].push(pid);
tree[pid] = [];
pidsToProcess[pid] = 1;
buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
});
};

ps.on('close', onClose);
}
Loading

0 comments on commit 6d8ac2b

Please sign in to comment.