Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ The options object can have the following properties:

- `signal` - an `AbortSignal` to allow aborting of the execution
- `timeout` - time in milliseconds at which the process will be forcibly killed
- `persist` - if `true`, the process will continue after the host exits
- `persist` - if `true`, the child process can continue after the host exits. By default, tinyexec terminates running children when the host exits normally or receives an unhandled `SIGINT`, `SIGTERM`, or `SIGHUP` on a platform that delivers it.
- `stdin` - `string` or another `Result` that will be used as the input to the process
- `nodeOptions` - any valid options to node's underlying `spawn` function
- `throwOnError` - if true, non-zero exit codes will throw an error
Expand Down
69 changes: 69 additions & 0 deletions src/host-exit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type {ChildProcess} from 'node:child_process';

const signals = ['SIGHUP', 'SIGINT', 'SIGTERM'] as const;
type HostSignal = (typeof signals)[number];
const isHostSignal = (event: string | symbol): event is HostSignal =>
signals.some((signal) => signal === event);

// Bundled or separately installed copies must share one set of signal handlers.
const trackerKey = Symbol.for('tinyexec.trackChild');
type TrackChild = (child: ChildProcess) => void;
const host = process as NodeJS.Process & {[trackerKey]?: TrackChild};

function createTracker(): TrackChild {
const children = new Set<ChildProcess>();
const terminate = () => {
for (const child of children) child.kill('SIGKILL');
};
const onSignal = (signal: HostSignal, signum?: number) => {
// Node supplies the signal number for OS signals. Applications can also emit the event.
if (typeof signum !== 'number') return;
host.removeListener(signal, onSignal);
terminate();
host.kill(host.pid, signal);
};

// Yield to application handlers, including one-shot handlers that do asynchronous
// work. Restore the default-exit fallback when the application removes its last one.
const onAdd = (event: string | symbol, listener: unknown) => {
if (isHostSignal(event) && listener !== onSignal) {
host.removeListener(event, onSignal);
}
};
const onRemove = (event: string | symbol, listener: unknown) => {
if (
isHostSignal(event) &&
listener !== onSignal &&
host.listenerCount(event) === 0
) {
host.on(event, onSignal);
}
};

return (child) => {
children.add(child);
if (children.size === 1) {
// Remove our fallback before Node starts watching a newly added application handler.
host.prependListener('newListener', onAdd);
host.on('removeListener', onRemove);
host.on('exit', terminate);
for (const signal of signals) {
if (host.listenerCount(signal) === 0) host.on(signal, onSignal);
}
}
child.once('exit', () => {
children.delete(child);
if (children.size > 0) return;
host.removeListener('newListener', onAdd);
host.removeListener('removeListener', onRemove);
host.removeListener('exit', terminate);
for (const signal of signals) host.removeListener(signal, onSignal);
Reflect.deleteProperty(host, trackerKey);
});
};
}

export function trackChild(child: ChildProcess): void {
const track = (host[trackerKey] ??= createTracker());
track(child);
}
4 changes: 4 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import {type Readable} from 'node:stream';
import {cwd as getCwd} from 'node:process';
import {computeEnv} from './env.js';
import {trackChild} from './host-exit.js';
import {combineStreams, readStream} from './stream.js';
import readline from 'node:readline';
import {normalizeSpawnCommand} from './normalize.js';
Expand Down Expand Up @@ -338,6 +339,9 @@ export class ExecProcess implements Result {
}

this._process = handle;
if (!options.persist && handle.pid !== undefined) {
trackChild(handle);
}
handle.once('error', this._onError);
handle.once('close', this._onClose);

Expand Down
54 changes: 54 additions & 0 deletions src/test/main_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,60 @@ const isWindows = os.platform() === 'win32';
const fixturesDir = path.join(import.meta.dirname, '../../test/fixtures');
const distDir = path.join(import.meta.dirname, '../../dist');

describe('host exits', () => {
function runHost(persist: boolean, exit: string) {
return spawnSync(
process.execPath,
[path.join(fixturesDir, 'host_exit.mjs'), String(persist), exit],
{encoding: 'utf8', timeout: 5000}
);
}

test.each([false, true])('normal exit with persist=%s', (persist) => {
const result = runHost(persist, 'exit');
expect(result.error).toBeUndefined();
expect(result.status).toBe(0);
expect(result.stdout).toBe(persist ? 'continued' : '');
});

test.skipIf(process.platform === 'win32')(
'unhandled SIGTERM terminates the host and child',
() => {
const result = runHost(false, 'SIGTERM');
expect(result.error).toBeUndefined();
expect(result.signal).toBe('SIGTERM');
expect(result.stdout).toBe('');
}
);

test.skipIf(process.platform === 'win32')(
'a one-shot SIGTERM handler can finish using the child',
() => {
const result = runHost(false, 'caught');
expect(result.error).toBeUndefined();
expect(result.status).toBe(31);
expect(result.stdout).toBe('');
}
);

test('emitting a signal event does not terminate the host', () => {
const result = runHost(false, 'synthetic');
expect(result.error).toBeUndefined();
expect(result.status).toBe(31);
});

test('separate copies release listeners after their children exit', () => {
const result = spawnSync(
process.execPath,
[path.join(fixturesDir, 'host_copies.mjs')],
{encoding: 'utf8', timeout: 5000}
);
expect(result.error).toBeUndefined();
expect(result.stderr).toBe('');
expect(result.status).toBe(0);
});
});

const variants = [
{name: 'async', x, isAsync: true},
{name: 'sync', x: xSync, isAsync: false}
Expand Down
22 changes: 22 additions & 0 deletions test/fixtures/host_copies.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import assert from 'node:assert/strict';
import {x as first} from '../../dist/main.mjs?first';
import {x as second} from '../../dist/main.mjs?second';

const events = [
'exit',
'SIGTERM',
'SIGINT',
'SIGHUP',
'newListener',
'removeListener'
];
const counts = () => events.map((event) => process.listenerCount(event));
const before = counts();
const args = ['-e', 'setTimeout(() => {}, 2000)'];
const a = first(process.execPath, args);
const b = second(process.execPath, args);
b.kill();
await b;
a.kill();
await a;
assert.deepEqual(counts(), before);
29 changes: 29 additions & 0 deletions test/fixtures/host_exit.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {x} from '../../dist/main.mjs';

const [persist, exit] = process.argv.slice(2);
const options = {
nodeOptions: {stdio: ['ignore', process.stdout, 'inherit', 'ipc']}
};
if (persist === 'true') options.persist = true;
if (exit === 'caught') {
process.once('SIGTERM', () => child.process.send('ping'));
}
const onDisconnect = `
process.on('message', () => process.send('pong'));
process.once('disconnect', () => process.stdout.write('continued'));
process.send('ready');
`;
const child = x(process.execPath, ['-e', onDisconnect], options);

child.process.on('message', (message) => {
if (message === 'pong') process.exit(31);
if (exit === 'synthetic') {
process.emit('SIGTERM');
process.emit('SIGTERM', 'SIGTERM');
child.process.send('ping');
} else if (exit !== 'exit') {
process.kill(process.pid, 'SIGTERM');
} else {
process.exit(0);
}
});