Austin
Austin

Reputation: 335

Child process isn't logging when receiving SIGINT

I am trying to kill a previously forked child process in Node.js. I'm unsure if it's working because my console.log line is not being hit in the child process.

Here is what I'm calling from the parent:

console.log("sending SIGINT from main");
child.kill("SIGINT");

And in the child:

process.on("SIGINT", () => {
  console.log("Killing bot");
  DBS.Bot.destroy();
  process.exit();
});

The only console log I see is from the parent.

Upvotes: 1

Views: 821

Answers (1)

Alexander Leithner
Alexander Leithner

Reputation: 3432

When spawning a NodeJS child process, this child process' stdout is not the same as the parent process' stdout stream, which is why you do not see any logging output. You can add the following code to copy any output of your child process to your main process' stdout stream:

child.stdout.on ("data", (data) => {
    console.log ("child process: " + data.toString ());
});

In some circumstances, it can be useful to also capture stderr output, which is the stream NodeJS' console.err () writes to:

child.stderr.on ("data", (data) => {
    console.log ("child process error: " + data.toString ());
});

Also, to make sure a child process has exited with a non-error code, i.e. the exit code is 0, you can use NodeJS' child_process "exit" signal:

child.on ("exit", (code, signal) => {
    if (signal !== null) console.log ("child exited due to signal '" + signal + "'");
    else console.log ("child exited with code " + code);
});

For more information, make sure to check out NodeJS' documenation on child_process.

Upvotes: 1

Related Questions