C - wait (NULL) value when performing fork () in parallel

In the code below, are the forks actually running in parallel or one after the other?

What's the point wait(NULL)

?

(The program creates n number of child processes, n is provided via the command line)

int main ( int argc, char *argv[] ) {
    int i, pid;

    for(i = 0; i < atoi(argv[1]); i++) {
        pid = fork();
        if(pid < 0) {
            printf("Error occured");
            exit(1);
        } else if (pid == 0) {
            printf("Child (%d): %d\n", i + 1, getpid());
            exit(0); 
        } else  {
            wait(NULL);
        }
    }
}

      

+3


source to share


1 answer


They run in parallel, right up to the moment when one of them is waiting.

wait(NULL)

or more precisely wait(0)

means to wait for the state to be changed in the child process. For Unix / Linux C api calls, type man <function Name>

at the command line. You will need to get used to reading these pages, so it's best to start now.

In your case



man wait

      

would give you what you need.

Since you only fork(...)

ed once, you only have one child. The parent waits until it changes state, and since the child state at the time of the fork is the same as the parent state before the fork (working) starts, the likely outcome is that the parent waits until the child dies. The parent will then continue execution, but since wait(...)

it won't do much after the call , it will exit quickly as well.

+4


source







All Articles