Skip to content

Commit

Permalink
Refactor childProcess.kill() to use async/await (#651)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Jan 6, 2024
1 parent 76ff50b commit 7701e9e
Showing 1 changed file with 14 additions and 19 deletions.
33 changes: 14 additions & 19 deletions lib/kill.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,32 @@ import {onExit} from 'signal-exit';
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;

// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
export const spawnedKill = (kill, signal = 'SIGTERM', {forceKillAfterTimeout = true} = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
const timeout = getForceKillAfterTimeout(signal, forceKillAfterTimeout, killResult);
setKillTimeout(kill, timeout);
return killResult;
};

const setKillTimeout = (kill, signal, options, killResult) => {
if (!shouldForceKill(signal, options, killResult)) {
const setKillTimeout = async (kill, timeout) => {
if (timeout === undefined) {
return;
}

const timeout = getForceKillAfterTimeout(options);
const t = setTimeout(() => {
kill('SIGKILL');
}, timeout);

// Guarded because there's no `.unref()` when `execa` is used in the renderer
// process in Electron. This cannot be tested since we don't run tests in
// Electron.
// istanbul ignore else
if (t.unref) {
t.unref();
}
await pSetTimeout(timeout, undefined, {ref: false});
kill('SIGKILL');
};

const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
const shouldForceKill = (signal, forceKillAfterTimeout, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;

const isSigterm = signal => signal === os.constants.signals.SIGTERM
|| (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
|| (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');

const getForceKillAfterTimeout = (signal, forceKillAfterTimeout, killResult) => {
if (!shouldForceKill(signal, forceKillAfterTimeout, killResult)) {
return;
}

const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
if (forceKillAfterTimeout === true) {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
Expand Down

0 comments on commit 7701e9e

Please sign in to comment.