Sending a socket to a forked process in Node.JS

If you want to fork a process in Node and pass a socket, the current Node documentation has a rather odd example, so I’ve simplified it here for my own sanity (further complicated by the fact that the WebStorm debugger can’t debug a forked Node.JS process, which confused me for too long). Hopefully someone else finds this useful at some point.

Step 1, in a file called app.js:

var child = require('child_process').fork('socket_handler.js');

// Open up the server and send sockets to child
var server = require('net').createServer();

server.on('connection', function (socket) {
    child.send('socket', socket);
    server.getConnections(function(err, count) {
        console.log("Connections: " + count);
    });
});
server.listen(1337);

And then, in a file called socket_handler.js which is located in the same directory as app.js:
process.on('message', function(message, socket) {
    socket.on('data', function(data) {
        // really poor echo ... :)
        socket.write(data);
    });
});

In this case, the fork happens upon application startup by calling the fork method of the child_process module. It starts by executing the code in socket_handler.js. As this is a new instance of the V8 engine used by Node.JS, remember there’s a sizable overhead to a forked process.

After creating the server and listening on port 1337, when a connection is made (which can be tested by a terminal emulator or telnet), the socket is passed to the forked process. In fact, it’s not really the object as much as it’s the handle to the new socket.

The send method takes two parameters, a string message which can be any identifier you want, and the the handle, or socket in this case.

The forked process receives the message via the message event on the process. If you’re sending more than one message, you can add conditional logic to handle the type of message in the event handler. As part of the call to fork, you can also pass command line arguments and read them using process.argv.

2 Comments

  1. Hello WiredPrairie,

    I have few questions on forking.
    1) What is the use of forking, why should we be using it ?
    2) Does the forked process is same as the main process ?

    Thanks
    Rajkamal

    1. There are a lot of good resources on the internet that explain forking reasonably well in far more detail than I’ll provide here. :)

      Quick answer:

      1. Node.JS is single threaded. There may be situations where using more than one process/thread could improve the performance of an application. Forking is the act of creating a child process that is a clone of the parent. It has all of the state/etc. of the parent, but in it’s own isolated container. Using an interprocess communication channel (often Pipes), the parent and child can communicate as necessary. That’s Linux/OSX. Now, Windows has a different model and doesn’t have the same functionality. In Windows, you can create a new process (CreateProcess) or a new thread (CreateThread). The difference when calling CreateProcess is that the child process does not inherit the state of of the parent. So, for Node.JS, when using child_process.fork, on Windows it’s going to create a new process and then initialize the Node engine in the new process. As it’s a new instance of the V8 engine anyway, the functional difference between the two operating systems is subtle.
      2. And by now, the answer to your second question should be more obvious as fork creates a new process on each operating system, just the technique is different.

      I believe the cluster module of Node uses forks to manage multiple processes.

Comments are closed.