创建并收获多个子进程

时间:2014-03-19 22:59:33

标签: c fork wait zombie-process

我一直无法弄清楚如何分叉多个(任何地方从10到200个)子进程,并让父进程等待所有这些进程完成。我试图对他们的累积执行时间进行基准测试。

尽管我付出了最大的努力,但是当我用顶部观看时,我已经得到了非常随机的结果和流程显示为“Z”(僵尸)。

我的代码如下,任何帮助将不胜感激。

int child_pid;
int status, wait_pid;

for(i = 0; i < instances; i++){
    if((child_pid = fork()) < 0){ // an error occured
        fprintf(stderr, "Fork failed\n");
        exit(EXIT_FAILURE);
    }
    if(child_pid == 0){ 
        // Child process --------------------------------------------------
        fprintf(stdout, "Child with PID: %d is in if code.", getpid());

        // Calculate pi using statistical methode across all iterations
        for(i=0; i<iterations; i++){
            x = (random() % (RADIUS * 2)) - RADIUS;
            y = (random() % (RADIUS * 2)) - RADIUS;
            if(zeroDist(x,y) < RADIUS){
                inCircle++;
            }

            inSquare++;
        }

        /* Finish calculation */
        pCircle = inCircle/inSquare;
        piCalc = pCircle * 4.0;

        /* Print result */
        fprintf(stdout, "pi = %f\n", piCalc);

        _Exit(EXIT_SUCCESS); //child is done ------------------------------
    }
}

//Parent Process
while ((wait_pid = wait(&status)) > 0){
    printf("Exit status of %d was %d \n", (int)wait_pid, status);
}

fprintf(stdout, "Bye from: %d.\n", getpid());
return 0;

编辑:

要测量我的结果,我只是使用Linux time命令从命令行调用该程序。

> /usr/bin/time ./pi-sched

EDIT2:

我的其余代码包含以下两个函数和一堆命令行解析和设置过程;没有其他与计算相关的东西。

inline double dist(double x0, double y0, double x1, double y1){
    return sqrt(pow((x1-x0),2) + pow((y1-y0),2));
}

inline double zeroDist(double x, double y){
    return dist(0, 0, x, y);
}

1 个答案:

答案 0 :(得分:0)

  当我用top观看时,

进程显示为'Z'(僵尸)。

这是因为除非你完成for(i = 0; i < instances; i++){循环,否则你不会开始等待子进程。要尽快等待子进程,您可以在waitpid(-1, &status, WNOHANG)循环中将该调用发送到for(),如果没有已终止的子进程,则此waitpid()将立即返回。

  

我的结果非常随机

程序的执行时间取决于以下代码的成本:

        x = (random() % (RADIUS * 2)) - RADIUS;
        y = (random() % (RADIUS * 2)) - RADIUS;
        if(zeroDist(x,y) < RADIUS){
            inCircle++;
        }

由于xy是一些随机值,因此上述代码的执行时间也可能随机变化。

相关问题