执行fork流程 [英] Execution of fork processes

查看:108
本文介绍了执行fork流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁将执行printf行(所有进程完成或每个进程之后的初始进程)?

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");
}

推荐答案

全部.从代码很简单.在任何已创建的子代中都不会调用exit(),并且它们可以自由执行父代执行的操作.因此,每个孩子都执行一次printf().可以通过以下方式进行编程验证:

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());
}

输出

$ ./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

从上面的输出中可以看出,每个创建的子代都执行一次printf().

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

这篇关于执行fork流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆