[英]Synchronizing sibling processes using Pipes
我正在使用管道學習IPC。 父進程創建'n'個子進程,並等待所有子進程終止。 我希望第一個孩子在所有兄弟姐妹進程終止時得到通知。 我正在利用read()
阻塞直到它的所有WRITE結束都被關閉的事實。 所以,兄弟姐妹close()
WRITE在完成他們的工作后結束。
我的代碼中的問題是,第一個子節點中的read()
根本沒有解除阻塞,並且第一個子節點沒有終止,因此父節點繼續等待。
我做錯了什么?
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
int fd[2]; // 0 = READ end, 1 = WRITE end
int ret = pipe(fd);
pid_t wait_pid;
int status = 0;
int n = 4;
for(volatile int i = 0;i < n;++i) {
ret = fork();
if(ret == -1) {
fprintf(stderr, "fork failed\n");
exit(1);
}
switch(ret) {
// child
case 0: {
fprintf(stderr, "Child created : %d\n", getpid());
if(i!=0) {
close(fd[0]); // close unused READ end
foo(); // do some work
close(fd[1]); // close WRITE end, the last child
// to close will cause the read()
// of first child to unblock
}
if(i==0) { // first child
close(fd[1]); // close unused WRITE end
foo(); // do some work
char c = 0;
fprintf(stderr, "1st Child's wait started %d\n",
getpid());
read(fd[0], &c, 1); // blocking call, until all
// siblings close the WRITE
// end
fprintf(stderr, "1st Child's wait over %d\n",
getpid());
close(fd[0]); // close READ end
}
fprintf(stderr, "Child %d terminating\n", getpid());
exit(0);
break;
}
}
}
// Parent waits for all childdren to finish
while ((wait_pid = wait(&status)) > 0);
fprintf(stderr, "Parent's wait over, now terminating...\n");
return 0;
}
您的技術的問題是父本身也有pipe
創建的文件描述符的副本。
fork
循環完成后關閉描述符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.