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.
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
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:
I believe the cluster module of Node uses forks to manage multiple processes.