C 使用管道同步同级进程
我在用管道学习IPC。父进程创建“n”个子进程,并等待所有子进程终止。我希望第一个孩子在其所有兄弟进程终止时得到通知。我利用了C 使用管道同步同级进程,c,linux,unix,pipe,ipc,C,Linux,Unix,Pipe,Ipc,我在用管道学习IPC。父进程创建“n”个子进程,并等待所有子进程终止。我希望第一个孩子在其所有兄弟进程终止时得到通知。我利用了read()阻塞直到所有写端都关闭的事实。因此,兄弟姐妹close() 我的代码中的问题是,第一个子项中的read()根本没有解除阻止,并且第一个子项没有终止,因此父项继续等待 我做错了什么 #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <
read()
阻塞直到所有写端都关闭的事实。因此,兄弟姐妹close()
我的代码中的问题是,第一个子项中的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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
int fd[2];//0=读取结束,1=写入结束
int ret=管道(fd);
不要等待;
int status=0;
int n=4;
对于(易失性int i=0;i0);
fprintf(stderr,“父级的等待结束,现在终止…\n”);
返回0;
}
您的技术的问题是父级本身也有一个由管道创建的文件描述符的副本
完成fork
循环后关闭描述符。您需要在子进程之间使用进程间通信(IPC),允许进程相互通信并同步其操作。我的程序就是这样做的,否:)为什么不使用一些同步原语,比如信号量?我可以。但我很好奇在上面的例子中我做错了什么:)可能是真棒的复制品!这很有帮助。谢谢!:)是的。我在Ubuntu上运行它(所以不允许只使用一个简短的“是”)