Reputation: 1058
I thought if I run this and then hit control-C, the program should exit after displaying "Exiting...". It does not. Of course, I want to do a lot more than console.log in the real application.
process.on('SIGINT', function() {
console.log("Exiting...");
process.exit();
});
while(1);
It does catch but does not exit. I have to kill the process separately.
Node version 8.x LTS
EDIT: The edit is to make one of my comments below clear.As is made clear in the accepted answer, my signal-handler was overwriting the default one but it was NEVER getting executed. The fact that Cntl-C was not killing the process gave me the impression that the signal-handler was actually executing. It had merely overwritten the built-in handler. THE ANSWER IS TRULY INFORMATIVE - PACKED WITH INFO IN A FEW WORDS.
Upvotes: 2
Views: 460
Reputation: 4694
while(1)
is hanging onto the process. Change it to:
setInterval(() => {}, 1000);
And it behaves as you would like.
I presume you used while(1)
as a placeholder for a running program, but it's not an accurate representation. A normal node app would not hold the process synchronously like that.
It's probably worth noting that when you execute process.on('SIGINT', ...
you are pre-empting node's normal SIGINT handler, which would have exited on ctrl-C even if while(1)
was holding the process. By adding your own handler, your code will run when node gets to it, which would be after the current synchronous event cycle, which in this case never happens.
Upvotes: 5