Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
", getpid());
        for(int i=0;i<3;i++) 
         {
                if (fork() == 0)
                        printf("PID = %d
", getpid());
         }
        while(wait(NULL)>0);
        printf("PID: %d finished
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...