2023-10-31 13:05:45 +00:00
|
|
|
import { promisify } from 'util'
|
|
|
|
import { spawn, exec } from 'child_process'
|
|
|
|
|
|
|
|
const execPromise = promisify(exec)
|
|
|
|
|
|
|
|
export default function kill(pid, signal) {
|
|
|
|
let pids = new Set()
|
|
|
|
let getSpawn = null
|
|
|
|
|
|
|
|
switch (process.platform) {
|
|
|
|
case 'win32':
|
|
|
|
return execPromise('taskkill /pid ' + pid + ' /T /F')
|
|
|
|
case 'darwin':
|
|
|
|
getSpawn = function(parentPid) {
|
|
|
|
return spawn('pgrep', ['-P', parentPid])
|
|
|
|
}
|
|
|
|
break
|
|
|
|
default:
|
|
|
|
getSpawn = function (parentPid) {
|
|
|
|
return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid])
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
return buildTree(pids, getSpawn, pid)
|
|
|
|
.then(function() {
|
|
|
|
for (let pid of pids) {
|
|
|
|
try {
|
|
|
|
process.kill(pid, signal)
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code !== 'ESRCH') throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function buildTree(allPids, spawnGetChildren, parentPid) {
|
2023-10-31 13:25:08 +00:00
|
|
|
allPids.add(parentPid)
|
2023-10-31 13:05:45 +00:00
|
|
|
|
|
|
|
let ps = spawnGetChildren(parentPid)
|
|
|
|
let data = ''
|
|
|
|
ps.stdout.on('data', function(buf) {
|
|
|
|
data += buf.toString('ascii')
|
|
|
|
})
|
|
|
|
|
|
|
|
return new Promise(function(res) {
|
|
|
|
ps.on('close', function(code) {
|
|
|
|
// Check if we got error code (usually means empty results)
|
|
|
|
if (code !== 0) return res()
|
|
|
|
|
|
|
|
res(Promise.all(
|
|
|
|
allData.match(/\d+/g)
|
|
|
|
.map(Number)
|
|
|
|
.filter(pid => !bla.has(pid))
|
|
|
|
.map(buildTree.bind(this, allPids, spawnGetChildren))
|
|
|
|
))
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|