Home > Blockchain >  How to interrupt child_process by a command given by parent process?
How to interrupt child_process by a command given by parent process?

Time:11-09

I am currently working on a project which requires the user to click on an 'execute' button to call a child_process in the backend for executing a time-consuming task. Codes are as follows,

let child = child_process.spawn(//args);
let data = '';
let err = '';
for await(const chunk of child.stdout) {
  data  = chunk;
}
for await(const chunk of child.stderr) {
  err  = chunk;
}
return {"out": data, "err": err};

Decoding is omitted here. The task of the child_process would output all results at the end of the process so there would be no output during the task is ongoing.

And the user interface has a button for the user to cancel the task while it is executing. I have tried if (cancelFlag) {child.kill('SIGTERM')} right after the child_process.spawn, but it would not work. I suppose a listener is needed for the child_process?

Great thanks for any suggestions.

CodePudding user response:

child_process.spawn accepts signal and killSignal in options for aborting process killSignal is SIGTERM by default, and the solution described in previous answers

But here is an example with signal and abort controller

let abortController = new AbortController();
let child = ChildProcess.spawn("sleep", ["1"], {
  signal: abortController.signal,
});
setTimeout(() => {
  abortController.abort();
}, 300);

CodePudding user response:

If you're using a POSIX system then sending SIGTERM to the child should kill the process by default.

However, on Windows SIGTERM is just available for listening and has no behavior by default https://nodejs.org/api/process.html#signal-events.

If you're programming on Windows you should be able to add a listener for the SIGTERM signal

  • Related