使用一个管道在父级和子级之间进行读写

时间:2013-04-12 07:56:49

标签: c ipc pipe

假设我有一个父进程分叉子进程,写入子进程,然后等待从子进程读取内容,我可以用一个管道实现吗?它看起来像是:

int main(){
    pid_t pid1;
    int pipefd[2];
    char data[]="some data";
    char rec[20]; 

    if(pipe(pipefd) == -1){
        printf("Failed to pipe\n");
        exit(0);
    }

    pid1 = fork();
    if(pid1<0){
         printf("Fork failed\n");
         exit(0);
    }else if(pid1==0){
        close(pipefd[1]);
        read(pipefd[0],rec,sizeof(rec));
        close(pipefd[0]);
        //do some work and then write back to pipe
        write(pipefd[1],data,sizeof(data));
    }else{
        close(pipefd[0]);
        write(pipefd[1],data,sizeof(data));
        close(pipefd[1]);
        //ignoring using select() for the moment.
        read(pipedfd[0],rec,sizeof(rec));
    }

当试图了解更多相关信息时,手册页指出管道是单向的。这是否意味着当您创建管道以在父级和子级之间进行通信时,写入管道的进程将无法再从中读取,并且从管道读取的进程无法再写入该管道?这是否意味着您需要两个管道才能进行来回通信?类似的东西:

  

PIPE1:

     

点---- -----读取&以及c

     

P&LT; --- -----写入ç

     

Pipe2:

     

点---- ----写入&以及c

     

P&LT; --- ------读ç

2 个答案:

答案 0 :(得分:4)

没有。根据定义,管道是单向的。问题是,如果没有任何同步,您将从同一个文件描述符中读取两个进程。但是,如果您使用信号量,则可以执行类似的操作

S := semaphore initiated to 0.
P writes to pipe
P tries down on S (it blocks)
P reads from pipe

C reads from pipe
C writes to pipe
C does up on S (P wakes up and continues)

另一种方法是使用两个管道 - 更容易。

答案 1 :(得分:1)

  

It is unspecified whether fildes[0] is also open for writing and whether fildes[1] is also open for reading

话虽如此,最简单的方法是使用两个管道。

另一种方法是通过管道指定子进程的文件描述符/名称/路径。在子进程中,您可以写入 filedes[1]中指定的文件描述符/名称/路径,而不是写入filedes[1]