DEV Community

Node.js fork is not what you think!

Pooya Parsa on January 24, 2019

Today I realized that in Node.js, neither cluster.fork or child_process.fork act like something you expect in a C environment. Actually, it is shor...
Collapse
 
littlefox profile image
Mara Sophie Grosch (LittleFox) • Edited

"Return value in the master process is always 0"

You mixed that up. Return value in the original process ("master") is the PID of the new process, the new process gets 0 as return value.

Ref manpages.ubuntu.com/manpages/bioni...

Collapse
 
pi0 profile image
Pooya Parsa

Yeah. You are right. I mixed up example code and blindly continued description based on it :D Thanks. Post Updated.

Collapse
 
thorx86 profile image
Athaariq Ardhiansyah

What operating system does under the hoods, is when we call fork(), it copies entire process state to a new one with a new PID.

The copy-on-write behavior still there, especially when you're running NodeJS under Linux-based machine. I already post the technical explanation at StackOverflow.

Collapse
 
blayman profile image
Brett

So the take home message is that Node spawns new processes rather than copying the current process? I'm using fork from child_process, and I expect it to create a new process with the file path that I pass into it, which it does. I guess that seems more straightforward than what you're describing with cluster.fork, which seems more specific to cluster based computing. I think it's quite common to use the if(master) check when you're doing cluster computing, because you're loading the same program on every node.