Created
February 4, 2012 20:35
-
-
Save AndreasMadsen/1740007 to your computer and use it in GitHub Desktop.
Frist draft on a simple javascript deamon
This file contains hidden or 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 child_process = require('child_process'); | |
function startDeamon(child, args) { | |
var newEnv = JSON.parse(JSON.stringify(process.env)); | |
newEnv.deamonOptions = JSON.stringify({exec: child, args: args}); | |
var deamonWatcher = child_process.fork(process.argv[1], ['deamon'], { | |
env: newEnv | |
}); | |
//deamonWatcher.independent(); | |
return deamonWatcher; | |
} | |
function setupProcess() { | |
process.on('disconnect', function () { | |
// since IPC is down, we may assume the deamon is dead | |
var options = JSON.parse(process.env.deamonOptions); | |
startDeamon(options.exec, options.args); | |
process.exit(0); | |
}); | |
} | |
// userland file | |
if (process.argv[2] === 'child') { | |
console.log('process: ' + process.pid); | |
setupProcess(); | |
// do something | |
var http = require('http'); | |
http.createServer(function (req, res) { | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end('Hello World\n'); | |
process.send('error'); | |
}).listen(1337, "127.0.0.1"); | |
} | |
// deamon file | |
else if (process.argv[2] === 'deamon') { | |
console.log('deamon: ' + process.pid); | |
var options = JSON.parse(process.env.deamonOptions); | |
var startProcess = function () { | |
var proc = child_process.fork(options.exec, options.args, { | |
env: process.env | |
}); | |
proc.on('exit', function (code) { | |
if (code !== null && code !== 0) { | |
startProcess(); | |
} | |
}); | |
proc.on('message', function () { | |
throw 'oh shit x2'; | |
}); | |
}; | |
startProcess(); | |
} | |
// module | |
else { | |
console.log('head: ' + process.pid); | |
// userland call | |
startDeamon(process.argv[1], ['child']); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment