Created
May 24, 2012 12:29
-
-
Save mmalecki/2781304 to your computer and use it in GitHub Desktop.
Quick and dirty zero-downtime process restart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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