Cluster: signal handler for worker process works?

381 views
Skip to first unread message

Jeong Heon

unread,
Aug 26, 2013, 3:17:32 AM8/26/13
to nod...@googlegroups.com
Hi, to make my service to do graceful shutdown,

I'm trying to write signal handler for worker processes(to flush buffered internal logs to external log server, etc.)

but they just dies without signal handling. I don't know why and how to fix this issue.

but code below is example. try running it and kill it(not Ctrl-C, use `kill [pid]`)

var cluster = require('cluster');

if (cluster.isMaster) {
  cluster.fork();
  function handleExit() {
    var id, w;
    for (id in cluster.workers) {
      w = cluster.workers[id];
      w.kill('SIGTERM');
    }
  };
  process.on('SIGTERM', handleExit);
  process.on('SIGINT', handleExit);
  return;
}

setInterval(function() {
  console.log('alive');
}, 1000);

process.on('SIGQUIT', function() {
  console.log('SIGQUIT');
});

process.on('SIGTERM', function() {
  console.log('SIGTERM!!!!');
});

process.on('SIGINT', function() {
  console.log('SIGINT!!!');
});

process.on('exit', function() {
  console.log('EXIT!!!');
});

process.on('message', function(msg) {
  console.log("Got Message " + msg);
});


Ben Noordhuis

unread,
Aug 26, 2013, 5:57:52 AM8/26/13
to nod...@googlegroups.com
The cluster module cleans up automatically when the master receives a
signal. What happens in your example is that the master process
instructs the worker process to commit suicide. When the worker
process goes away, there is nothing to keep the event loop alive and
node.js subsequently exits (that's why you get the 'exit' event - it's
just a normal shutdown.)

Admittedly the above could be explained a little better in the cluster
module documentation. There is an open pull request for that that I
should probably merge. :-)

But anyway, to make a long story short: have a listener like the one
below in your code and you should be good. The implementation of
allWorkersGone() is left as an exercise to the reader. :-)

cluster.on('disconnect', function(worker) {
if (allWorkersGone()) cleanup();
});
Reply all
Reply to author
Forward
0 new messages