Search code examples
coperating-systemforkwait

Execution of fork processes


Who will execute the printf line (the initial process after all processes finished or every process)?

#include<stdio.h> 
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    for(int i=0;i<3;i++) 
    {
        fork();
    }
    while(wait(NULL)>0);
    printf("finished\n");
}

Solution

  • All. It is straightforward from the code. No exit() is called in any created child and they are free to execute what parent executes. So each child executes printf() once. This can be programmatically verified as below:

    #include<stdio.h> 
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    
    
    int main()
    {
    
            printf("PID = %d\n", getpid());
            for(int i=0;i<3;i++) 
             {
                    if (fork() == 0)
                            printf("PID = %d\n", getpid());
             }
            while(wait(NULL)>0);
            printf("PID: %d finished\n", getpid());
    }
    

    OUTPUT

    $ ./a.out 
    PID = 120360
    PID = 120361
    PID = 120362
    PID = 120364
    PID = 120363
    PID = 120366
    PID: 120363 finished
    PID: 120366 finished
    PID = 120367
    PID = 120365
    PID: 120367 finished
    PID: 120365 finished
    PID: 120362 finished
    PID: 120364 finished
    PID: 120361 finished
    PID: 120360 finished
    

    From the above output, it can be seen that each created child is executing printf() once.