Created
April 30, 2018 09:56
-
-
Save adisbladis/35549403a59cd5033b0deca610c9bf37 to your computer and use it in GitHub Desktop.
Finding child processes recursive in nodejs without external dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const ChildProcess = require('child_process') | |
function findChildren(pid) { | |
const pgrep = ChildProcess.spawnSync('pgrep', ['-P', pid]) | |
// Probably segfault.. | |
// Happens on linux at least when there is no child | |
if(pgrep.status === null) { | |
return [] | |
} | |
const pids = pgrep | |
.stdout | |
.toString() | |
.split('\n') | |
.filter(x => x) | |
const subPids = pids.map(findChildren) | |
return [].concat.apply(pids, subPids) | |
} | |
const pid = process.argv[2] | |
if(pid === undefined) { | |
console.error(`Usage: ${process.argv[1]} <pid>`) | |
process.exit(1) | |
} | |
findChildren(pid).map(pid => { | |
const command = ChildProcess.spawnSync('ps', ['-o', 'command=', pid]).stdout.toString().trim() | |
const exec = command.split(/\s/)[0] | |
return {pid: parseInt(pid), exec, command} | |
}) | |
.map(proc => { | |
console.log(proc) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment