I don't understand signal behaviour in node. SIGINT Ctrl-C
- Version: v14.15.4: v14.15.4
- Platform: Fedora 33 5.10.8-200.fc33.x86_64
- Scope code: runtime
Ctrl-C does work here
// Complete one line program. Ctl-C works
while(true) {}
But not here
// Complete two lines program. Ctl-C does not work
process.on('SIGINT',function() {process.exit()})
while(true){}
I am a begginer in node, and have read the documentation about node event loop, but I don't understand why first program quits, and second one not.
Hi, in second case event loop is blocked by while loop and does no processes callbacks
To expand on that a bit:
In the first case, there is no SIGINT handler. Because there is no SIGINT handler, when Ctrl+C is presset, the operating system performs the default action for SIGINT and terminates the process.
In the second case, Node.js registers a SIGINT handler. Because the operating system wouldn’t let Node.js run JavaScript inside an event handler (for good reasons), Node.js instead schedules the callback to be called as soon as possible instead of running it immediately when it sees SIGINT. As @rodion-arr said, this happens on the event loop, and since the while(true){} loop never returns control to the event loop, that callback is never run.
So in the first case it is the parent process that processes the signal. bash process actually. Thanks a lot.
No. As @addaleax explained, it is the OS that provides the default implementation for that signal on behalf of a userland process. The signal occurs only in the context of the process, as aided/assisted by the operating system. Installing a signal handler effectively provides a replacement for the OS default implementation; only one handler is so installed, and therefore for multiple handlers to be supported each handler must co-operate in forming signal chains to provide opportunity for actions to be taken. The parent process is not informed of the signal, and would not be able to intervene on behalf of the child as enforced by process isolation; the only knowledge gained by the parent would be knowing the child process terminated.
This is testable: you could implement a signal handler in your parent bash shell, and demonstrate that is it not aware or involved in handling the signal of the child process. They are totally independent.