Since a function in C returns only one value, all the time, how can fork()
, which is also a function, return two values?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With