Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bnoordhuis
Forked from AndreasMadsen/deamontest.js
Created February 5, 2012 22:35
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 bnoordhuis/1748236 to your computer and use it in GitHub Desktop.
Save bnoordhuis/1748236 to your computer and use it in GitHub Desktop.
Frist draft on a simple javascript deamon
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