user507401 user507401 - 1 year ago 93
C Question

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

Since a function in C returns only one value, all the time, how can

, which is also a function, return two values?

Answer Source

If you read, build, and run the following program you should get a better idea of what is going on.

#include <stdio.h>
#include <unistd.h>

int main(void) {
    pid_t fk;

    printf("\tbefore fork my pid = %lu\n", (unsigned long)getpid() );

    fflush(stdout); /* This may keep the above print
                       statement from outputing twice. */

    fk = fork(); /* The OS kernel makes a copy of the current process here */

    printf("fork returned %lu and now my pid = %lu\n",
                         (unsigned long)fk, (unsigned long)getpid() );

    return 0;

The reason that the fflush(stdout) is needed is that since the process is duplicated by fork that means that the buffering done for stdout by stdio is duplicated as well. The "\n" at the end of that first print statement may make it go ahead and flush stdout, but this isn't guaranteed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download