Skip to content

It is hard to safely kill a process #249

@junm-cloudnatix

Description

@junm-cloudnatix

Expected Behavior

The processPromise has the method kill to terminate a process. However, zx will raise UnhandledPromiseRejectionWarning by calling it. A code like:

const proc = $`sleep 10`;
await sleep(1000);
proc.kill();

should finish without warnings.

Actual Behavior

It finishes with:

$ sleep 10
(node:1154335) UnhandledPromiseRejectionWarning: Error: 
    at file:///path/to/foo.mjs:3:15
    exit code: null
    at ChildProcess.<anonymous> (file:///home/junm/.nvm/versions/node/v14.18.1/lib/node_modules/zx/index.mjs:89:22)
    at ChildProcess.emit (events.js:400:28)
    at maybeClose (internal/child_process.js:1058:16)
    at Socket.<anonymous> (internal/child_process.js:443:11)
    at Socket.emit (events.js:400:28)
    at Pipe.<anonymous> (net.js:686:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1154335) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1154335) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Also, it can't simply be caught, i.e.

const proc = $`sleep 10`;
await sleep(1000);
proc.kill().catch(console.log);

still raises the same warning.

proc.catch(...).kill()

does not work, as the returned value of catch misses some properties (it reports Cannot read property 'pid' of undefined).

Steps to Reproduce the Problem

Already described above.

Workaround

I found it's possible to wrap the processPromise like follows:

const wrapKill = (processPromise) => {
	const kill = processPromise.kill.bind(processPromise);
	const p = processPromise.catch(err => {
		console.log('killed: ', err);
	});
	p.kill = kill;
	return p;
};
const task = wrapKill($`sleep 10`);
await sleep(2000);
task.kill();

This finishes without warnings. However, I don't think this is a great API to allow killing a process safely.

Specifications

  • Version: zx version 4.2.0
  • Platform: node.js v14.18.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions