"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.pids = exports.kill = exports.pidExists = void 0; const node_child_process_1 = __importDefault(require("node:child_process")); const node_process_1 = __importDefault(require("node:process")); const Object_1 = require("./Object"); const Platform_1 = require("./Platform"); /** * @param {number} pid process id. Required. * @returns boolean true if the given process id is in the local process * table. The PID may be paused or a zombie, though. */ function pidExists(pid) { if (pid == null || !isFinite(pid) || pid <= 0) return false; try { // signal 0 can be used to test for the existence of a process // see https://nodejs.org/dist/latest-v18.x/docs/api/process.html#processkillpid-signal return node_process_1.default.kill(pid, 0); } catch (err) { // We're expecting err.code to be either "EPERM" (if we don't have // permission to send `pid` and message), or "ESRCH" if that pid doesn't // exist. EPERM means it _does_ exist! if ((err === null || err === void 0 ? void 0 : err.code) === "EPERM") return true; // failed to get priority--assume the pid is gone. return false; } } exports.pidExists = pidExists; /** * Send a signal to the given process id. * * @export * @param pid the process id. Required. * @param force if true, and the current user has * permissions to send the signal, the pid will be forced to shut down. Defaults to false. */ function kill(pid, force = false) { if (pid == null || !isFinite(pid) || pid <= 0) return false; try { return node_process_1.default.kill(pid, force ? "SIGKILL" : undefined); } catch (err) { if (!String(err).includes("ESRCH")) throw err; return false; // failed to get priority--assume the pid is gone. } } exports.kill = kill; const winRe = /^".+?","(\d+)"/; const posixRe = /^\s*(\d+)/; /** * Only used by tests * * @returns {Promise} all the Process IDs in the process table. */ function pids() { return new Promise((resolve, reject) => { node_child_process_1.default.execFile(Platform_1.isWin ? "tasklist" : "ps", // NoHeader, FOrmat CSV Platform_1.isWin ? ["/NH", "/FO", "CSV"] : ["-e"], (error, stdout, stderr) => { if (error != null) { reject(error); } else if (("" + stderr).trim().length > 0) { reject(new Error(stderr)); } else resolve(("" + stdout) .trim() .split(/[\n\r]+/) .map((ea) => ea.match(Platform_1.isWin ? winRe : posixRe)) .map((m) => (0, Object_1.map)(m === null || m === void 0 ? void 0 : m[0], parseInt)) .filter((ea) => ea != null)); }); }); } exports.pids = pids; //# sourceMappingURL=Pids.js.map