Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...