Skip to content

Instantly share code, notes, and snippets.

@mmalecki
Created May 24, 2012 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmalecki/2781304 to your computer and use it in GitHub Desktop.
Save mmalecki/2781304 to your computer and use it in GitHub Desktop.
Quick and dirty zero-downtime process restart
var http = require('http'),
fork = require('child_process').fork;
var serverHandle, server;
function log(l) {
console.log(process.pid + ': ' + l);
}
process.on('SIGUSR2', function () {
log('rolling restart');
var child = fork(__filename);
child.send('handle', server._handle);
child.on('message', function (m) {
if (m === 'listening') {
log('child listening, quitting');
server.close();
}
});
});
if (process.send) {
log('running as a child');
process.on('message', function (m, handle) {
if (m === 'handle') {
serverHandle = handle;
}
});
}
else {
serverHandle = 8000;
}
log('delaying server start...');
setTimeout(function () {
log('server starting.');
server = http.createServer(function (req, res) {
log('request');
res.end('Hello world, process id: ' + process.pid + '\n');
});
server.listen(serverHandle, function () {
log('listening on ' + server.address().port);
if (process.send) {
process.send('listening');
}
});
}, 2048);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment