2

For a typical C program, we do something like this to create a new process:

int main(void)
{
    pid_t childPID;

    childPID = fork();

   if(childPID >0){
       do something
   }
   else if(childPID == 0){
        do something
   }
   else {
        do something
   }
}

but in a node.js program, the fork is usually done in the if statement:

var cluster = require('cluster');

if (cluster.isMaster) {
    do something
    cluster.fork()
}
else{
    do something for the child process
}

Why we can create child processes in the if statement in Node.js? Why does not the child process skip the else block?

Thanks!

silverwen
  • 287
  • 3
  • 11
  • I assume this is because `cluster.fork` causes the child processes to execute from the top of the program (unlike C's `fork` which causes execution starting from the next line after the `fork()`), but I'm not 100% sure. – apsillers Dec 28 '15 at 13:02

1 Answers1

4

It's because C fork() and node.js cluster.fork() work in a different way.

In C fork() creates an exact duplicate of a current process (except for the fork() returned value) and then continue execution of both processes from the point when fork() was called.

In node.js cluster.fork() spawns new worker node.js process with the same .js entry point, but using somewhat different environment. It also establishes an IPC channel for passing messages/file descriptors between master process and its workers.

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
  • So do you mean that the child process executes from the top of the program as @apsillers says? – silverwen Dec 30 '15 at 04:46
  • Yes, because `cluster.fork()` uses [`child_process.fork()` function](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options) to spawn another node.js instance. It's not cloning current process, like C does, it spawns a brand new one. – Leonid Beschastny Dec 30 '15 at 09:13