Search code examples
javascriptnode.jsmultiprocessingforknode-cluster

Why is the "Hello world" printed 2 times?


Why dose the program print "Hello World" 2 times rather than only 1 time? The console.log is excuted before cluster.fork().

import * as cluster from "cluster";

console.log("Hello World");

if (cluster.isMaster) {
    const worker = cluster.fork();
    worker.disconnect();
}

The following c program prints "Hello World" only 1 time

#include <unistd.h>
#include <stdio.h>
int main(void)
{
   printf("HelloWorld/n");
   fork();
   return 0;
}

Solution

  • The cluster.fork method (through child_process.fork, which it calls) does not do a fork syscall like you'd have in UNIX. It does create a new child process, like fork would, but that new child process starts with an entirely new instance of the interpreter, and that new interpreter starts executing the script from the beginning. You're seeing the console.log executed once in the parent process and once in the child process.

    The docs for child_process.fork briefly mention this...

    Unlike the fork(2) POSIX system call, child_process.fork() does not clone the current process.

    ...but I would still say the name is confusing.

    To work around this, you will probably want to move your initialization logic (in this example the console.log call) into the if (cluster.isMaster) block.