tags:

views:

129

answers:

3

We know that a c function never returns more than one value.Then how come the fork() function returns two values? How it is implemented?

+3  A: 

The fork() function starts a new process by duplicating the current one. If it works, fork() returns one thing from the parent process and another thing from the child process so that the remaining code knows which process is "this" process.

fork(), in a sense, does return two values, but not in the same sense as you might be thinking. Another function that does this type of thing is setjmp() (which returns 0 if returning directly and non-zero if we got here via longjmp()).

For a C function to return two values in the sense you're talking about, it is often done like this:

int return_2_values(int *other)
{
    *other = 2;
    return 1;
}

and invoked like this:

int b;
int a = return_2_values(&b);

/* a is now 1, and b is now 2 */

Here, return_2_values() is passing both return values to the same continuation, whereas fork() and setjmp() return one value each to two different continuations.

Joey Adams
Another way you return multiple values is by returning a pointer to a structure that could then contain multiple values.
Paul Rubel
+4  A: 

fork() as a function only returns one value at a time - however, it creates a copy of your running executable, and returns a different value in each copy.

Nicholas M T Elliott
This might clarify: http://www.opengroup.org/onlinepubs/000095399/functions/fork.html
You
+1  A: 

fork() only returns one value. It just returns different values different processes.

The implementation of this behavior is managed by the OS.

dmckee