Linux – How does Node.js / the cluster module pass new connections from the master / parent process, to child processes

clinuxnode.jsunix-sockets

How exactly does this work under the hood / at the OS level (primarily in Unix implementations / from the perspective of the sockets API)?

The cluster module documentation says:

"the master process listens on a port, accepts new connections and distributes them across the workers in a round-robin fashion"

Does this mean the master process alone handles / calls accept() on incoming connections, and then passes the returned socket descriptor to a pre-forked child process via some IPC mechanism (Unix domain sockets?), where it's presumably registered with a local (to that process) multiplexing mechanism (e.g. an epoll instance)?

I'm trying to gain a better understanding of the inner workings of Node.js, but can't find a whole lot of definitive info at this level. Any help is much appreciated.

Thanks

Best Answer

See child.send() in the nodejs child_process module. In a nutshell, you do:

child.send('socket', socket);

Where 'socket' is a special message name and you send a reference to the nodejs socket object. Nodejs then handles things under the covers in the child_process module for sending the actual OS socket handle to the child process and then hooking up a new nodejs socket object to it on the other end of things.

And, here's a reference to an article on the topic: Sending a socket to a forked process in Node.JS.

Related Question