UNPKG

kill-sync

Version:

Cross-platform kill command. Supports recusive/tree-kill in a synchronous manner.

84 lines 2.62 kB
"use strict"; /** * Code below is inspired by tree-kill-sync and tree-kill: * - https://github.com/dvpnt/tree-kill-sync/blob/master/index.js * - https://github.com/pkrumins/node-tree-kill/blob/master/index.js */ Object.defineProperty(exports, "__esModule", { value: true }); exports.treeKill = exports.killPid = void 0; const child_process_1 = require("child_process"); /** * Retrieves a list of all running process IDs (PIDs) along with their parent * process IDs (PPIDs). * * @returns {PID_ITEM[]} An array of PID_ITEM objects containing PID and PPID. */ const getAllPids = () => (0, child_process_1.execSync)('ps -A -o pid=,ppid=') .toString() .trim() .split('\n') .map((row) => { var _a; const [, pid, ppid] = (_a = row.match(/\s*(\d+)\s*(\d+)/)) !== null && _a !== void 0 ? _a : []; return { pid: Number(pid), ppid: Number(ppid) }; }); /** * Retrieves all child PIDs of a given parent PID. * * @param {number} parentPid - The parent PID for which to find child PIDs. * @returns {number[]} An array of child PIDs. */ const getAllChilds = (parentPid) => { const all = getAllPids(); const ppidHash = all.reduce((hash, item) => { hash[item.ppid] = (hash[item.ppid] || []).concat(item.pid); return hash; }, {}); const result = []; const recursivelAddChild = (pid) => { ppidHash[pid] = ppidHash[pid] || []; ppidHash[pid].forEach((childPid) => { result.push(childPid); recursivelAddChild(childPid); }); }; recursivelAddChild(parentPid); return result; }; /** * Kills a process with the specified PID using the given signal. * The error ESRCH will be ignored. * * @param {number} pid - The PID of the process to be killed. * @param {number | string} signal - The signal to send for termination. */ const killPid = (pid, signal) => { try { process.kill(pid, signal); } catch (err) { if (err.code !== 'ESRCH') { throw err; } } }; exports.killPid = killPid; /** * Recursively kills a process and all its child processes using the specified * signal - i.e. terminates the whole process tree. * * @param {number} pid - process pid to be killed alongside children. * @param {number | string} signal - the signal to send for termination. */ const treeKill = (pid, signal) => { const childs = getAllChilds(pid); childs.forEach((pid) => { (0, exports.killPid)(pid, signal); }); (0, exports.killPid)(pid, signal); }; exports.treeKill = treeKill; //# sourceMappingURL=treekill.js.map