6

Is it possible to intercept the default kill signal and use it as a command for a graceful shutdown? This is for Solaris SMF. The easiest way to have a stoppable service that I have found is to set :kill as the shutdown script and then to add a shutdown hook in Java. In this case, I want to do it for Node.JS. How should I do it?

Edit: The purpose is to

  1. Stop receiving new requests.
  2. Give existing callbacks a few seconds to finish.
  3. Write some information to stderr.

@alienhard's first suggestion was to use process.on('exit'... but it seems that I would not be able to accomplish number 2 with this method.

700 Software
  • 85,281
  • 83
  • 234
  • 341

2 Answers2

14

There is an exit event: http://nodejs.org/docs/v0.3.1/api/process.html#event_exit_

process.on('exit', function() {
  console.log('About to exit.');
});

Edit: An alternative that could work for you, is instead of killing the process, sending a signal like SIGUSR1 (kill -s SIGUSR1), and then listening for this signal (see link posted by @masylum in another answer) and after you are done or some time has elapsed explicitly terminate with process.exit().

alienhard
  • 14,376
  • 9
  • 37
  • 28
  • 3
    It the docs say *"The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled."*. If I understand correctly, I will not be able to use `setTimeout` or other events or callbacks. Is that correct? If that is correct, I would like instead to have a callback where I can delay the exit by several seconds and allow other callbacks to finish. Is there such a thing? – 700 Software Mar 22 '11 at 20:23
  • This didn't work on windows. Should I even be trying it on anything but *nix? ;-) – Ustaman Sangat Feb 28 '12 at 22:30
5

The only thing that comes to my mind is using signal events.

http://nodejs.org/docs/v0.3.1/api/process.html#signal_Events

masylum
  • 22,091
  • 3
  • 20
  • 20