我有8个孩子,我正在尝试使用8对nonduplex无名管道与他们沟通。因此,每个子节点有2个管道,总共有16个管道(一个用于childRead_ParentWrite,另一个用于parentRead_ChildWrite)。
无论如何,我的主要问题是何时关闭管道。我被教导最初关闭那些没有被过程使用的侧面,然后当过程完成它的管道侧面时,关闭它。但是,我是这个主题的新手,我遇到了一些麻烦。这是我的代码:
// The 16 pipes
int fd_childReads_ParentWrites[8][2]; // Parent closes 0, Child closes 1
int fd_parentReads_ChildWrites[8][2]; // Child closes 0, Parent closes 1
// The 16 buffers
char buf_ChildReads_ParentWrites[8][80];
char buf_ParentReads_ChildWrites[8][80];
// CREATE THE PIPES
// FORK THE CHILDREN
for(playerNumber = 0; playerNumber < NUM_PLAYERS; playerNumber++)
{
pid = fork();
if (pid < 0) // Error occurred
{
printf("Fork Failed\n");
exit(1);
}
else if (pid == 0) // Child
{
break;
}
}
// MANAGE PROCESSES
if (pid == 0) // CHILD
{
printf("I am the child: %d\n", getpid());
// Close the appropriate pipe ends
close(fd_childReads_ParentWrites[playerNumber][1]);
close(fd_parentReads_ChildWrites[playerNumber][0]);
// CHILD DOES STUFF WITH PIPES
// When finished, close the working child pipe ends
close(fd_childReads_ParentWrites[playerNumber][0]);
close(fd_parentReads_ChildWrites[playerNumber][1]);
}
else // PARENT
{
printf("I am the parent: %d\n", getpid()); // NOT BEING PRINTED
// Close the appropriate pipe ends
for (i = 0; i < NUM_PLAYERS; i++)
{
close(fd_childReads_ParentWrites[i][0]);
close(fd_parentReads_ChildWrites[i][1]);
}
// PARENT DOES STUFF WITH PIPES
// Finally, close the working parent pipe ends
for (i = 0; NUM_PLAYERS < 8; i++)
{
close(fd_childReads_ParentWrites[i][1]);
close(fd_parentReads_ChildWrites[i][0]);
}
// Wait for the children
for (playerNumber = 0; playerNumber < NUM_PLAYERS; playerNumber++)
{
wait(NULL);
}
}
我一定是做错了。该程序打印出正确数量的子项,但从不打印父项的printf()行。当我取出它打印的所有close()函数时,即使仅仅取出孩子们的close()也不打印父行。
如果有人能够向我解释在这种情况下关闭nonduplex未命名管道的正确方法,那就太棒了。