【问题标题】:Create pipes after fork在 fork 之后创建管道
【发布时间】:2012-01-20 20:45:09
【问题描述】:

这样做是否可能/正确?如果我从“子”进程的 fd1[1] 进行写入,那么是否可以从“父”进程的 fd2[0] 读取?

main(){
    pid_t pid;
    pid = fork();
    if(pid <0){
        return -1;
    }
    if(pid == 0){
        int fd1[2];
        int fd2[2];
        pipe(fd1);
        pipe(fd2);
        close fd1[1];
        close fd2[0];
        //writes & reads between the fd1 pipes
        //writes & reads between the fd2 pipes
    }else{
        int fd1[2];
        int fd2[2];
        pipe(fd1);
        pipe(fd2);
        close fd1[1];
        close fd2[0];
        //writes & reads between the fd1 pipes
        //writes & reads between the fd2 pipes
    }
}

【问题讨论】:

  • 那么你的问题是什么?我看起来不像是你自己无法测试的东西。

标签: c fork pipe


【解决方案1】:

不,用于进程间通信的管道应该在fork() 之前创建(否则,你没有简单的方法通过它们发送,因为读取和写入端应该由不同的过程)。

在进程之间发送文件描述符作为套接字上的带外消息有一些肮脏的技巧,但我真的忘记了细节,这很难看

【讨论】:

    【解决方案2】:

    您需要在分叉之前设置管道

    int fds[2];
    
    if (pipe(fds))
        perror("pipe");
    
    switch(fork()) {
    case -1:
        perror("fork");
        break;
    case 0:
        if (close(fds[0])) /* Close read. */
            perror("close");
    
        /* What you write(2) to fds[1] will end up in the parent in fds[0]. */
    
        break;
    default:
        if (close(fds[1])) /* Close write. */
            perror("close");
    
        /* The parent can read from fds[0]. */
    
        break;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-25
      • 2011-01-26
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多