Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible for fork() to return two values?

Since a function in C returns only one value, all the time, how can fork(), which is also a function, return two values?

like image 920
user507401 Avatar asked Nov 17 '10 18:11

user507401


2 Answers

The fork function returns 0 to the child process that was created and returns the childs ID to the parent process.

The two seperate processes are each returned a single value.

So think of it more as one return being called on each thread process.

like image 66
Jake Kalstad Avatar answered Oct 01 '22 01:10

Jake Kalstad


As Gnostus says, the fork() function does not return two values.

What it does is return a single value, the way all functions do, but it returns twice.

Once within the parent process and once within the child. The parent process gets the child's process ID returned to it, the child gets 0 - an invalid process ID, so the code can tell it is the child.

The child is a new process, running the same code and is at the same place in the code as the parent that spawned it.

int cProcessID;

cProcessID = fork();

if (cProcessID == 0) {
    // Child process
} else {
    // Parent process
}
like image 45
Orbling Avatar answered Oct 01 '22 02:10

Orbling