ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

使用管道同步同级进程

2019-11-10 21:00:55  阅读:168  来源: 互联网

标签:unix c-3 linux pipe ipc


我正在使用管道研究IPC.父进程创建n个子进程,并等待所有子进程终止.我希望第一个孩子在所有同级进程终止时得到通知.我正在利用read()阻塞直到所有WRITE结束都被关闭这一事实.因此,兄弟姐妹在完成工作后将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; 
}

解决方法:

您的技术存在的问题是,父级本身也具有管道创建的文件描述符的副本.

fork循环完成后,关闭描述符.

标签:unix,c-3,linux,pipe,ipc
来源: https://codeday.me/bug/20191110/2015052.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有