Skip to content
Myr

kill.js

This file

Path

lib/kill.js

92 lines · 2.2 KiB · JavaScript

Last changed by

Separate spawned.kill() features into own file (#312)ehmickybefore adoption230c7a7

History of this file

Take it

Separate spawned.kill() features into own file (#312)ehmickybefore adoption230c7a7

lines 1–92why, one step back
1'use strict';
2const os = require('os');3const onExit = require('signal-exit');45const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;67// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior8const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {9 const killResult = kill(signal);10 setKillTimeout(kill, signal, options, killResult);11 return killResult;12};1314const setKillTimeout = (kill, signal, options, killResult) => {15 if (!shouldForceKill(signal, options, killResult)) {16 return;17 }1819 const timeout = getForceKillAfterTimeout(options);20 setTimeout(() => {21 kill('SIGKILL');22 }, timeout).unref();23};2425const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {26 return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;27};2829const isSigterm = signal => {30 return signal === os.constants.signals.SIGTERM ||31 (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');32};3334const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {35 if (forceKillAfterTimeout === true) {36 return DEFAULT_FORCE_KILL_TIMEOUT;37 }3839 if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {40 throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);41 }4243 return forceKillAfterTimeout;44};4546// `childProcess.cancel()`47const spawnedCancel = (spawned, context) => {48 const killResult = spawned.kill();4950 if (killResult) {51 context.isCanceled = true;52 }53};5455// `timeout` option handling56const setupTimeout = (spawned, {timeout, killSignal}, context) => {57 if (timeout > 0) {58 return setTimeout(() => {59 context.timedOut = true;60 spawned.kill(killSignal);61 }, timeout);62 }63};6465// `cleanup` option handling66const setExitHandler = (spawned, {cleanup, detached}) => {67 if (!cleanup || detached) {68 return;69 }7071 return onExit(() => {72 spawned.kill();73 });74};7576const cleanup = (timeoutId, removeExitHandler) => {77 if (timeoutId !== undefined) {78 clearTimeout(timeoutId);79 }8081 if (removeExitHandler !== undefined) {82 removeExitHandler();83 }84};8586module.exports = {87 spawnedKill,88 spawnedCancel,89 setupTimeout,90 setExitHandler,91 cleanup92};