简体   繁体   中英

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;
}

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.

cluster.fork creates a new child process and executes the same code. You should check if the process is the master or not and then execute code that you want inside either the if block or else block.

import * as cluster from "cluster";


if (cluster.isMaster) {
    console.log("Hello World from master");
    const worker = cluster.fork();
    worker.disconnect();
} else {
    console.log("Hello World from others");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM