Skip to content

Instantly share code, notes, and snippets.

@adisbladis
Created April 30, 2018 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adisbladis/35549403a59cd5033b0deca610c9bf37 to your computer and use it in GitHub Desktop.
Save adisbladis/35549403a59cd5033b0deca610c9bf37 to your computer and use it in GitHub Desktop.
Finding child processes recursive in nodejs without external dependencies
#!/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