Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a child process from within itself in Node.JS

Is there a way to kill make a child process "suicide"? I tried with process.exit(1) but apparently it kills the whole application I'm running. I just want to kill the child process (like when we call process.kill() from the "father" of the child process). Also calling process.kill() within the child process kills the whole application.

Any idea?

like image 425
Masiar Avatar asked Oct 22 '22 22:10

Masiar


1 Answers

process is always a reference to the main process. But you can simply use this:

var spawn = require( "child_process" ).spawn;

// example child process
var grep = spawn( "grep", [ "ssh"] );

grep.on( "exit", function (code, signal) {
    console.log( "child process terminated due to receipt of signal "+signal);
});

grep.kill( "SIGHUP" );

I guess it depends on how you use child processes. But if you don't have a reference to the child process, then there is not much you can do.

WARNING: Killing child processes is almost never a good idea. You should send a message to the child processes and handle it in that process.

like image 168
freakish Avatar answered Oct 27 '22 11:10

freakish