学习如何使用fork()命令以及如何在父级和子级之间传输数据。我正在尝试编写一个简单的程序来测试fork和pipe函数的工作方式。我的问题似乎是等待函数的正确使用/放置。我希望父母等待其两个孩子完成处理。下面是代码我迄今:如何在分叉多个进程时使用wait()函数?
int main(void)
{
int n, fd1[2], fd2[2];
pid_t pid;
char line[100];
if (pipe(fd1) < 0 || pipe(fd2) < 0)
{
printf("Pipe error\n");
return 1;
}
// create the first child
pid = fork();
if (pid < 0)
printf("Fork Error\n");
else if (pid == 0) // child segment
{
close(fd1[1]); // close write end
read(fd1[0], line, 17); // read from pipe
printf("Child reads the message: %s", line);
return 0;
}
else // parent segment
{
close(fd1[0]); // close read end
write(fd1[1], "\nHello 1st World\n", 17); // write to pipe
// fork a second child
pid = fork();
if (pid < 0)
printf("Fork Error\n");
else if (pid == 0) // child gets return value 0 and executes this block
// this code is processed by the child process only
{
close(fd2[1]); // close write end
read(fd2[0], line, 17); // read from pipe
printf("\nChild reads the message: %s", line);
}
else
{
close(fd2[0]); // close read end
write(fd2[1], "\nHello 2nd World\n", 17); // write to pipe
if (wait(0) != pid)
printf("Wait error\n");
}
if (wait(0) != pid)
printf("Wait error\n");
}
// code executed by both parent and child
return 0;
} // end main
目前我输出看起来沿着线的东西:
./fork2
Child reads the message: Hello 1st World
Wait error
Child reads the message: Hello 2nd World
Wait error
哪里是合适的地方,使家长等待?
感谢,
托梅克
你好,我正在做一个目前使用管道的项目。你能否解释一下当main处于最后一个else语句时,main是如何将信息传递给你的第一个子进程的? – TwilightSparkleTheGeek 2014-06-25 18:41:57