选择()仍然阻止管道读取 [英] Select() still blocks read from pipe

查看:147
本文介绍了选择()仍然阻止管道读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序叉一个孩子,孩子execls一个新的程序,父写,然后读取来自孩子接回孩子完成一些工作之后。当监视管道的读结束时,程序仍然等待子。我目前不写回父,所以故意将阻止。下面是code(所述write_to()函数关闭管道的未使用的部分中的功能):

My application forks a child, the child execls a new program, the parent writes to it, and then reads back from the child after the child performs some work. When monitoring the read end of the pipe, the program still waits for the child. I'm currently not writing back to the parent, so it intentionally would block. Below is the code (the write_to() function closes the unused parts of the pipe in the function):

    pid_t leaf_proc;


    int rv = 0;

    int w_pfd[2];
    int r_pfd[2];   

    if(pipe(w_pfd) == -1 || pipe(r_pfd) == -1){
        printf("Failed to pipe. Goodbye.\n");
        exit(0);
    }

    if((leaf_proc = fork()) < 0){
        printf("Error: %s\n",strerror(errno));
        exit(0);
    }else if(leaf_proc == 0){
        /***Child to be execl()'d***/
        rv = execl("Some program");
        if(rv < 0){
            printf("Error: %s\n",strerror(errno));
            exit(0);
        }
    }else{
        /***Parent***/
        write_to(par_info,w_pfd);
        fd_set read_set;
        //struct timeval tv;
        //tv.tv_sec = 5;
        //tv.tv_usec = 0;

        FD_ZERO(&read_set);
        FD_SET(r_pfd[0], &read_set);
        rv = select(r_pfd[0]+1,&read_set,NULL,NULL,&tv);
        printf("set?: %d\n",rv);
     }

在运行此,该程序仍挂在select语句(永​​远不会达到去年的printf),但如果我添加超时信息,节目5秒后继续进行。首先,我使用的选择是否正确?第二,虽然这可能不是会阻止(在这个意义上,父进程不会由内核中断,不它仍然导致的结果(过程直到挂的东西准备好)?

When running this, the program still hangs at the select statement (last printf is never reached), but if I add timeout info, the program continues after 5 seconds. First of all, am I using select correctly? And second, while this may not be blocking (in the sense that the parent process won't be interrupted by the kernel, doesn't it still result in the outcome (process hanging until something is ready)?

推荐答案

您必须关闭管道的未使用的部分在这两个孩子,在父进程。

You have to close the unused parts of the pipe in both the child and in the parent process.

终止管道写FD将在子进程被关闭,但在父它仍然是开放的,所以你的选择会耐心等待数据之后。 ...

After terminating the write fd of the pipe will be closed in the child process, but in the parent it is still open, so your select will patiently wait for data....

这篇关于选择()仍然阻止管道读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆