【问题标题】:Unidirectional pipes in CC中的单向管道
【发布时间】:2017-02-24 05:13:43
【问题描述】:

我在尝试弄清楚如何为父进程和子进程创建单独的管道以单向方式运行时遇到了麻烦。即:父级的描述符和子级的不同描述符。

这是我所拥有的:

#include <sys/types.h>

int main(int argc, char *argv[]) {

    int parent[2];
    int child[2];
    pid_t pid;

    int num = 0;

    pipe(parent);
    pipe(child);

    pid =fork();

    if(pid > 0){ // do parent stuff

        num = 5;

        write(parent[1], &num, sizeof(num));
        printf("Parent with pid %d sent value: %d\n", getpid(), num);

        close(parent[1]);

    }else{ // do child stuff

        read(child[0], &num, sizeof(num));
        printf("Child with pid %d received value: %d\n", getpid(), num);

        close(child[0]);

        exit(0);
    }
    return 0;
}

输出:

Parent with pid 31702 sent value: 5

我知道我应该在 read() 和 write() 命令之前的某个时间点关闭一些描述符,但似乎无论我关闭子响应打印之前父可以@987654325 @ 或者我最终会遇到一个坏掉的管道。我应该在哪里关闭描述符才能成功地单向使用这些管道?

【问题讨论】:

    标签: c pipe fork parent-child child-process


    【解决方案1】:

    简而言之,这不是您应该使用管道的方式。

    管道具有read 0 和write 1 端。

    在您的情况下,孩子正在阅读child[0],但没有人会通过child[1] 给孩子写信。家长要写信给parent[1]。

    尝试使用单个管道(将 child[0] 更改为 parent[0])。并确保删除您不会在各个流程中使用的末端

    【讨论】:

    • 所以不可能有一个管道给父母,另一个给孩子,并且仍然有成功的 IPC?
    • 你可以用一个管道做IPC
    • 父级分叉N次怎么办?我将如何从父母与每个孩子沟通?
    • 为每个孩子制作一根烟斗
    • 那么在那种情况下,这就是我上面的方式吗?
    【解决方案2】:

    您正在制作两个管道,然后只使用它们的一端;沟通不起作用,因为没有人关注任何一方的另一端。 parent 和 child 是完全独立的管道,您发送的内容不会出现在另一个管道上。您只需要一根管道:

    int main(int argc, char *argv[]) {
    
        int pipefd[2];
        pid_t pid;
    
        int num = 0;
    
        pipe(pipefd);
    
        pid = fork();
    
        if(pid > 0){ // do parent stuff
            close(pipefd[0]); // close the reading end
    
            num = 5;
    
            write(pipefd[1], &num, sizeof(num)); // write on the writing end
            printf("Parent with pid %d sent value: %d\n", getpid(), num);
    
        }else{ // do child stuff
            close(pipefd[1]); // close the writing end
    
            read(pipefd[0], &num, sizeof(num)); // read on the reading end
            printf("Child with pid %d received value: %d\n", getpid(), num);
    
            exit(0);
        }
        return 0;
    }
    

    管道已经是单向的,它给了你两个端点:一个写端和一个读端。你只需要适当地使用每一个。

    【讨论】:

    • 单向是指管道只能用于读取或写入;不是都在同一个管道上。
    • @DarrelHolt 管道有两端。一端的东西从另一端出来。否则,它不会完全有用。
    • 我想如果不是这样,它就不会被称为管道。感谢您澄清并提供代码示例。
    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多