C-并行执行fork()时wait(NULL)的含义 [英] C - meaning of wait(NULL) when executing fork() in parallel

查看:1509
本文介绍了C-并行执行fork()时wait(NULL)的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,分支实际上是并行运行还是一个接一个地运行?

In the code below, do the forks actually run in parallel or one after another?

wait(NULL)是什么意思?

(程序创建了n个子进程,n通过命令行提供)

(The program creates an n number of child processes, n is supplied via 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);
        }
    }
}

推荐答案

它们确实并行运行,直到其中一个等待.

They do run in parallel, up until the point that one of them waits.

wait(NULL)或更准确地说wait(0)表示等待,直到子进程的状态更改.要了解有关Unix/Linux C api调用的信息,请在命令行上键入man <function Name>.您需要习惯于阅读这些页面,所以现在就更好地开始吧.

wait(NULL) or more accurately wait(0) means wait until a state change in the child process. To find out about Unix / Linux C api calls, type man <function Name> on the command line. You'll need to get used to reading those pages, so better start now.

以您的情况

man wait

会给您您所需要的.

由于您只进行过一次fork(...),因此您只有一个孩子.父级会一直等到它更改状态为止,并且由于分叉过程中子级的状态与分叉前父级的状态( running 的状态)相同,因此可能的结果是父级会一直等到孩子死了.然后,父级将继续执行,但是由于wait(...)调用后不需要做太多事情,它也会很快退出.

Since you've only fork(...)ed once, you have only one child. The parent waits until it changes state, and since the child's state during the fork is the same as the parent's state prior to the fork (that of running), the likely outcome is that the parent waits until the child dies. Then the parent will continue executing, but since it doesn't have much to do after the wait(...) call, it will quickly exit too.

这篇关于C-并行执行fork()时wait(NULL)的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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