Pages

Tuesday, August 22, 2017

Kill the Child Process when Parent Process exists in NodeJS

Kill the Child Process when Parent Process exists in NodeJS

  • There may be some cases where we may want to exit the child process, if the parent process quits gracefully.
  • SIGINT / SIGKILL cannot be detected by NodeJS or even from the Linux - C API.
  • These two signals are at the kernel space, hence cannot be detected from the User Space.
  • But these two signals can be sent to the Child process by the Parent Process.
  • SIGTERM ( graceful Shutdown ) can be detected by NodeJS. The following sample code explain how to capture graceful shutdown and kill the child process.

child.js

var sleep=require("sleep");
 

while(1){
console.log(" I m child process");
sleep.sleep(1);
}


Parent.js

const  spawnObj = require('child_process');
const child = spawnObj.fork('/home/user1/test/child.js');



process.on('SIGTERM', function () {
  console.log('Got SIGTERM.  Press Control-D to exit.');
   child.kill('SIGINT');
});




Run the Parent.js code and press CTRL + D.
When  CTRL+ D is pressed, child process is killed when the parent process exits.

 

No comments:

Post a Comment