Skip to content

Instantly share code, notes, and snippets.

@bnoordhuis
Forked from AndreasMadsen/deamontest.js
Created February 5, 2012 22:35
Show Gist options
  • Select an option

  • Save bnoordhuis/1748236 to your computer and use it in GitHub Desktop.

Select an option

Save bnoordhuis/1748236 to your computer and use it in GitHub Desktop.

Revisions

  1. Andreas Madsen created this gist Feb 4, 2012.
    74 changes: 74 additions & 0 deletions deamontest.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@

    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']);

    }