Skip to content

Commit

Permalink
Refactor kill() (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky authored and sindresorhus committed Jun 10, 2019
1 parent 6c0a400 commit a7b57d9
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,23 @@ function joinCommand(file, args = []) {
return [file, ...args].join(' ');
}

function spawnedKill(kill, signal = 'SIGTERM', options = {}) {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
}

function setKillTimeout(kill, signal, options, killResult) {
if (!shouldForceKill(signal, options, killResult)) {
return;
}

const forceKillAfter = Number.isInteger(options.forceKillAfter) ?
options.forceKillAfter :
5000;
setTimeout(() => kill('SIGKILL'), forceKillAfter).unref();
}

function shouldForceKill(signal, options, killResult) {
return ((typeof signal === 'string' &&
signal.toUpperCase() === 'SIGTERM') ||
Expand All @@ -239,20 +256,8 @@ const execa = (file, args, options) => {
}));
}

const originalKill = spawned.kill.bind(spawned);
spawned.kill = (signal = 'SIGTERM', options = {}) => {
const killResult = originalKill(signal);
if (shouldForceKill(signal, options, killResult)) {
const forceKillAfter = Number.isInteger(options.forceKillAfter) ?
options.forceKillAfter :
5000;
setTimeout(() => {
originalKill('SIGKILL');
}, forceKillAfter).unref();
}

return killResult;
};
const kill = spawned.kill.bind(spawned);
spawned.kill = spawnedKill.bind(null, kill);

// #115
let removeExitHandler;
Expand Down

0 comments on commit a7b57d9

Please sign in to comment.