Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js, process.kill() and process.exit(0), which one can kill process?

Tags:

node.js

I read node.js docs. It says:

Even though the name of this function is process.kill(), it is really just a signal sender, as the kill system call. The signal sent may do something other than killing the target process.

console.log('current process id: ', process.pid);

process.on('SIGHUP', function() {
  console.log('Got SIGHUP signal');
});

setTimeout(() => {
  console.log('Exiting...');
  process.exit(0);  //kill process
  console.log('Process id that has exited: ', process.pid); //does not output
}, 1000);

process.kill(process.pid, 'SIGHUP'); //does not kill process
console.log('Id of the process exiting: ', process.pid); //so this output normally

output:

current process id:  64520
Id of the process exiting:  64520
Got SIGHUP signal
Exiting...

It seems process.exit(0) is the one which kills node.js process.

like image 464
slideshowp2 Avatar asked Mar 07 '18 03:03

slideshowp2


3 Answers

It all depends on the situation that you're in. Like Gospal Joshi said process.exit([code]) is useful to end the process very quickly. But in other cases you may want to pass a signal to that process before shutdown for cleanup/graceful shutdown. For example if you are listening to signal events such as:

process.on('SIGINT', () => {
  //do something
}

it allows you to run cleanup or gracefully shutdown the process vs exiting instantly without doing anything.

Also, note that Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js processes will not terminate immediately due to receipt of those signals. Rather, Node.js will perform a sequence of cleanup actions and then will re-raise the handled signal - Node Documentation

like image 63
Mike Mulligan Avatar answered Sep 19 '22 09:09

Mike Mulligan


Use process.exit(), It ends the process with the specified code. Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending

Syntax: process.exit([code])

Links:

  1. Exit codes
  2. Exit() Documentation
like image 38
Gopal Joshi Avatar answered Sep 19 '22 09:09

Gopal Joshi


process.kill(pid, [ code ]) shines on concurrent applications with multiple processes (since you can just plug in the pid of the process you wish to kill and it does it).

process.exit() is sufficient and most common if you dont have a usecase that requires killing any other process than the main node process.

Personally, I recommend you to use process.exit() unless you really have to kill another process (pid different than process.pid)

like image 41
Tibebes. M Avatar answered Sep 21 '22 09:09

Tibebes. M