perry_VW
perry_VW

Reputation: 145

Use one pipe to read and write between parent and child

Assuming I have a parent process that forks a child process, writes to the child, and then waits to read something from the child, can I implement this with one pipe? It would look something like:

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));
    }

When trying to learn more about this, the man pages state that pipes are unidirectional. Does this mean that when you create a pipe to communicate between a parent and child, the process that writes to the pipe can no longer read from it, and the process that reads from the pipe can no longer write to it? Does this mean you need two pipes to allow back and forth communication? Something like:

Pipe1:

P----read----->C

P<---write-----C

Pipe2:

P----write---->C

P<---read------C

Upvotes: 2

Views: 4821

Answers (2)

Anish Ramaswamy
Anish Ramaswamy

Reputation: 2351

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

That being said, the easiest way would be to use two pipes.

Another way would be to specify a file descriptor/name/path to the child process through the pipe. In the child process, instead of writing to filedes[1], you can write to the file descriptor/name/path specified in filedes[1].

Upvotes: 1

Adrian
Adrian

Reputation: 1176

No. Pipes by definition are one-way. The problem is, that without any synchronization you will have both processes reading from the same filedescriptor. If you, however, use semaphores you could do something like that

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)

The other way is to use two pipes - easier.

Upvotes: 4

Related Questions