2015-09-04 62 views
1

这是我的代码。基本上,我有很多孩子,他们应该从ptList中计算出一定数量的点数,将相应的点数传递给父级,父级将这些点数加起来。不幸的是,对于我的printf,“addToTotal”变量没有更新过第一个孩子,我的回答不正确。任何建议都会令人难以置信。通过来自多个孩子的管道写入父进程

pid_t worker[ workers ]; 
for (int i = 0; i < workers; i++) { 
//printf("I am child %i\n", i); 
if ((worker[i] = fork()) < 0) { 
    fail("Can't create child"); 
} else if (worker[i] == 0) { 
    //Close the reading end of the pipe for each child 
    close(pfd[0]); 

    // Get each of the workers to compare points 
    for (int k = i; k < ptCount; k += workers) { 
     for (int j = k + 1; j < ptCount; j++) { 
     int dx = ptList[ k ].x - ptList[ j ].x; 
     int dy = ptList[ k ].y - ptList[ j ].y; 
     if (dx * dx + dy * dy <= dsq) 
      childTotal++; 
     } 
    } 
    printf("Child %i total: %i\n", i, childTotal); 
    lockf(pfd[ 1 ], F_LOCK, 0); 
    write(pfd[ 1 ], &childTotal, sizeof(childTotal)); 
    lockf(pfd[ 1 ], F_ULOCK, 0); 
    close(pfd[ 1 ]); 
    exit(0); 
    wait(NULL); 
} 
wait(NULL); 
close(pfd[ 1 ]); 
read(pfd[ 0 ], &addToTotal, sizeof(addToTotal)); 
printf("AddToTotal: %i\n", addToTotal); 
total += addToTotal; 
} 
+0

在循环的第一次迭代中,父级关闭管道的写入侧。在第二次迭代中,子级继承了写入侧关闭的管道。 –

回答

0

在循环的第一次迭代中,父级关闭管道的写入端。在第二次迭代中,子级继承了写入侧关闭的管道。你不能关闭循环内的写入端,所以你需要第二个循环来完成读取操作。

1

的孩子获得在其上写侧被关闭的管道,因为该行你expliciltly关闭:

close(pfd[ 1 ]); 

,然后在接下来的迭代中再次尝试写入管道:

write(pfd[ 1 ], &childTotal, sizeof(childTotal)); 
相关问题