學習如何使用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