Improve `taskkill` usage (#1258)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent 5944b2d · Browse files · 2 files·+156 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+156 added−6 removed
- tests:+125 added−0 removed
- other:+31 added−6 removed
Provenance
- Commit
3d9d820- Tree
bc31259- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
5944b2d
2 files changed+156 added−6 removed
modified:lib/terminate/kill-descendants.js+31 added-6 removed
123456732 unmodified lines40414243434445464445464748495051525152535455565758596061626364656667686970717273747576777879import process from 'node:process';import {execFile} from 'node:child_process';import path from 'node:path/win32';
const isWindows = process.platform === 'win32';
// The `killDescendants` option terminates the whole process tree, not just the direct child.32 unmodified lines }};
// Windows has no process groups. Instead, `taskkill /T` recursively terminates the process tree.// It must run while the tree is still intact, so it is the only termination performed: killing the// direct subprocess first would orphan its descendants before `taskkill` could enumerate them.// Windows does not support signals, so the signal argument is ignored (`/F` terminates the tree).const killDescendantsWindows = subprocess => {// It must run while the tree is still intact, so direct subprocess termination is only used as a// fallback: killing the direct subprocess first would orphan its descendants before `taskkill` could enumerate them.// If `taskkill` is unavailable or fails, the fallback only terminates the direct subprocess.// `taskkill` ignores the signal (`/F` terminates the tree).const killDescendantsWindows = (subprocess, signal) => { if (subprocess.pid === undefined) { return false; }
// This is best-effort: any error (such as the subprocess having already exited) is ignored. execFile('taskkill', ['/pid', `${subprocess.pid}`, '/T', '/F'], () => {}); const taskkillFile = getTaskkillFile(); if (taskkillFile === undefined) { return subprocess.kill(signal); }
// This is best-effort: if `taskkill` fails, still try the direct subprocess. execFile(taskkillFile, ['/pid', `${subprocess.pid}`, '/T', '/F'], error => { if (error) { subprocess.kill(signal); } }); return true;};
export const getTaskkillFile = () => { const windowsDirectory = [process.env.SystemRoot, process.env.windir] .find(directory => directory && isWindowsDriveAbsolutePath(directory));
return windowsDirectory === undefined ? undefined : path.join(windowsDirectory, 'System32', 'taskkill.exe');};
const isWindowsDriveAbsolutePath = directory => { const {root} = path.parse(directory); return /^[a-z]:[/\\]/i.test(root);};modified:test/terminate/kill-descendants.js+125 added
1+import childProcess from 'node:child_process';2+import {syncBuiltinESMExports} from 'node:module';3+import path from 'node:path/win32';4 import process from 'node:process';5 import {setTimeout} from 'node:timers/promises';6 import test from 'ava';7 import isRunning from 'is-running';8 import {execa, execaSync} from '../../index.js';9+import {getTaskkillFile} from '../../lib/terminate/kill-descendants.js';10 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11 12 setFixtureDirectory();13 77 unmodified lines91 t.throws(() => {92 execaSync('empty.js', {killDescendants: true});93 }, {message: /The "killDescendants: true" option cannot be used/});94 });95+96+test.serial('taskkill is resolved from the Windows directory when available', t => {97+ const {SystemRoot, windir} = process.env;98+ t.teardown(() => {99+ restoreEnvironment('SystemRoot', SystemRoot);100+ restoreEnvironment('windir', windir);101+ });102+103+ process.env.SystemRoot = 'C:\\Windows';104+ process.env.windir = 'D:\\Windows';105+ t.is(getTaskkillFile(), path.join('C:\\Windows', 'System32', 'taskkill.exe'));106+107+ process.env.SystemRoot = 'C:/Windows';108+ t.is(getTaskkillFile(), path.join('C:/Windows', 'System32', 'taskkill.exe'));109+110+ process.env.SystemRoot = 'Windows';111+ t.is(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));112+113+ process.env.SystemRoot = '\\Windows';114+ t.is(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));115+116+ delete process.env.SystemRoot;117+ t.is(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));118+119+ process.env.windir = 'Windows';120+ t.is(getTaskkillFile(), undefined);121+122+ process.env.windir = '\\Windows';123+ t.is(getTaskkillFile(), undefined);124+125+ process.env.windir = '\\\\server\\share\\Windows';126+ t.is(getTaskkillFile(), undefined);127+128+ process.env.windir = '';129+ t.is(getTaskkillFile(), undefined);130+131+ delete process.env.windir;132+ t.is(getTaskkillFile(), undefined);133+});134+135+test.serial('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {136+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');137+ const {SystemRoot, windir} = process.env;138+ t.teardown(() => {139+ Object.defineProperty(process, 'platform', platformDescriptor);140+ restoreEnvironment('SystemRoot', SystemRoot);141+ restoreEnvironment('windir', windir);142+ });143+144+ Object.defineProperty(process, 'platform', {value: 'win32'});145+ process.env.SystemRoot = 'Windows';146+ delete process.env.windir;147+148+ const {getKillFunction} = await import(`../../lib/terminate/kill-descendants.js?taskkill-fallback=${Date.now()}`);149+ let killedWith;150+ const subprocess = {151+ pid: 123,152+ kill(signal) {153+ killedWith = signal;154+ return true;155+ },156+ };157+158+ const kill = getKillFunction(subprocess, {killDescendants: true});159+ t.true(kill('SIGTERM'));160+ t.is(killedWith, 'SIGTERM');161+});162+163+test.serial('taskkill fallback uses direct subprocess kill when taskkill cannot be spawned', async t => {164+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');165+ const originalExecFile = childProcess.execFile;166+ const {SystemRoot, windir} = process.env;167+ t.teardown(() => {168+ Object.defineProperty(process, 'platform', platformDescriptor);169+ childProcess.execFile = originalExecFile;170+ syncBuiltinESMExports();171+ restoreEnvironment('SystemRoot', SystemRoot);172+ restoreEnvironment('windir', windir);173+ });174+175+ Object.defineProperty(process, 'platform', {value: 'win32'});176+ process.env.SystemRoot = 'C:\\MissingWindows';177+ delete process.env.windir;178+179+ const taskkillFailure = Promise.withResolvers();180+ childProcess.execFile = (file, arguments_, callback) => {181+ t.is(file, path.join('C:\\MissingWindows', 'System32', 'taskkill.exe'));182+ t.deepEqual(arguments_, ['/pid', '123', '/T', '/F']);183+ queueMicrotask(() => {184+ callback(new Error('spawn failed'));185+ taskkillFailure.resolve();186+ });187+ };188+189+ syncBuiltinESMExports();190+191+ const {getKillFunction} = await import(`../../lib/terminate/kill-descendants.js?taskkill-spawn-fallback=${Date.now()}`);192+ let killedWith;193+ const subprocess = {194+ pid: 123,195+ kill(signal) {196+ killedWith = signal;197+ return true;198+ },199+ };200+201+ const kill = getKillFunction(subprocess, {killDescendants: true});202+ t.true(kill('SIGTERM'));203+ t.is(killedWith, undefined);204+205+ await taskkillFailure.promise;206+ t.is(killedWith, 'SIGTERM');207+});208+209+const restoreEnvironment = (name, value) => {210+ if (value === undefined) {211+ delete process.env[name];212+ } else {213+ process.env[name] = value;214+ }215+};