Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forking in NodeJS

I'm a little bit confused as to how to create daemons in NodeJS

I've created daemons in C before that call fork() that continue execution from where the call was made in a child process allowing the parent to terminate. I can't readily achieve the same affect using process.fork() and process.kill().

The following code doesn't do what I expected and breaks:

var current_pid, cp = require('child_process');
current_pid = process.pid;
cp.fork('');
process.kill(current_pid);

The following error is emitted and I can't work out why or what's happening:

node.js:202
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: read EBADF
    at errnoException (net.js:589:11)
    at Pipe.onread (net.js:335:20)

The problem call appears to be process.kill(). Removing this, both processes continue to happily run.

I'm aware of daemon.node, but this was created at the time when child_process.fork() didn't exist (v0.1.33 was the version available when daemon.node was written). Now there is a native way to fork, so this should no longer be necessary. (Plus, it appears to have been abandoned too.)

like image 908
Matty Avatar asked Oct 27 '11 00:10

Matty


1 Answers

child_process.fork() has a totally misleading name and is not the same as C’s fork().

According to the docs, it executes a Node.js script as a child process and sets up a communications channel between the calling process and the child. That's it.

The actual spawning of the child process is done inside libuv, Node's “platform layer,” in C, and fork() itself is not exposed to Node scripts.

A simple, much-improvable way to daemonize using only what’s built-in to Node.js might look like this:

if (process.argv[2] !== 'child') {
    require('child_process').execFile(process.argv[0], [__filename, 'child']);
    process.exit();
}

setTimeout(function(){
    console.log('foo');
}, 5000);

Obviously, this is pretty different from fork(). If daemon.node works for you, keep using it.

like image 70
s4y Avatar answered Sep 23 '22 06:09

s4y