Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process.on('SIGINT' multiple termination signals

Tags:

node.js

i have this node code that detect when Ctrl+C in pressed to that do some stuff before node app is exit

process.on('SIGINT', function() {
    /* DO SOME STUFF HERE */

    process.exit()
})

Now this works but i would like to add to this process others terminations signals so that when Ctrl+C, Node app exits or server is restarted or shutdown or any other reason node app exits to trigger termination signal and call this process and do stuff in database before exits...

termination signals that i need to add is:

SIGTERM
SIGINT
SIGQUIT
SIGKILL

So i came to idea if is possible to do this:

 process.on('SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGKILL', function() {
        /* DO SOME STUFF HERE */

        process.exit()
 })

So to pass multiple termination signals to process function..i added like this above but it does not work...how can this be done in node js?

like image 266
John Avatar asked Oct 24 '17 11:10

John


People also ask

How do you SIGINT a process?

Pressing Ctrl+C sends an Interrupt signal (SIGINT) to the process and the process terminates. Restart it. Pressing Ctrl+Z sends a STOP signal (SIGTSTP) to the process which kind of freezes/pauses the process and the shell prompt returns.

Does the signal SIGINT end the process that is currently running?

SIGINT is the signal sent when we press Ctrl+C. The default action is to terminate the process. However, some programs override this action and handle it differently.

Which of the following signals have usually same result as the SIGINT signal?

SIGINT is nearly identical to SIGTERM. The SIGTSTP signal is sent to a process by its controlling terminal to request it to stop temporarily. It is commonly initiated by the user pressing Ctrl-Z. Unlike SIGSTOP, the process can register a signal handler for or ignore the signal.

What is process CWD?

process. cwd() returns the current working directory, i.e. the directory from which you invoked the node command. __dirname returns the directory name of the directory containing the JavaScript source code file.


2 Answers

The easiest method:

['SIGINT', 'SIGTERM', 'SIGQUIT']
  .forEach(signal => process.on(signal, () => {
    /** do your logic */
    process.exit();
  }));
like image 178
Alexandru Olaru Avatar answered Sep 24 '22 13:09

Alexandru Olaru


I'd rather go with

/**
 * Do stuff and exit the process
 */
function signalHandler() {
    // do some stuff here
    process.exit()
}

process.on('SIGINT', signalHandler)
process.on('SIGTERM', signalHandler)
process.on('SIGQUIT', signalHandler)

for style and clarity reasons

like image 24
sezanzeb Avatar answered Sep 22 '22 13:09

sezanzeb