Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which end of a pipe is for input and which for output?

Recently I started suspecting that I use the ends of the pipes wrongly:

From the man pages:

pipe() creates a pipe.. ..pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.

So in my mind I had it like this:

                .---------------------------.
               /                            /\
              | pipedfd[0]       pipedfd[1]|  |
process1 ---> |                            | -----> process2
              | input                output|  |
               \____________________________\/

However the code that I have here and works suggests otherwise:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
  int pipedfd[2];
  char buf[30];

  pipe(pipedfd);
  printf("writing to file descriptor #%d\n", pipedfd[1]);
  write(pipedfd[1], "test", 5);
  printf("reading from file descriptor #%d\n", pipedfd[0]);
  read(pipedfd[0], buf, 5);
  printf("read \"%s\"\n", buf);

  return 0;
}

Namely it writes to the output(?) of the pipe and reads from the input(?) of the pipe?

like image 952
Pithikos Avatar asked Oct 23 '11 15:10

Pithikos


1 Answers

In a nutshell, swap the numbers 0 and 1 in your diagram and you got what I'll describe below.

From the Mac OS X man page:

The pipe() function creates a pipe (an object that allows unidirectional data flow) and allocates a pair of file descriptors. The first descriptor connects to the read end of the pipe; the second connects to the write end.

Data written to fildes[1] appears on (i.e., can be read from) fildes[0]. This allows the output of one program to be sent to another program: the source's standard out- put is set up to be the write end of the pipe; the sink's standard input is set up to be the read end of the pipe. The pipe itself persists until all of its associated descriptors are closed.

I'll describe how it's often used, that might clear it up. Imagine you have a process and want to spawn a child, to which you want to send commands.

  • First, you call pipe and get the two file descriptors.
  • Then you call fork to create the child.
    • In the child, you close the writing file descriptor (fd[1]) and leave the reading one open.
    • In the parent, you do the reverse: you close the reading (fd[0]) file descriptor and leave the writing one open.
  • Now the parent can write into "his" part of the pipe (fd[1]) and the child can read on the other (fd[0]).

The closing is not necessary but is usually done. If you need two-way communication you either need a second set of file descriptors plus a second call to pipe, or you use a two way channel like Unix domain sockets or a named pipe.

like image 133
DarkDust Avatar answered Oct 23 '22 09:10

DarkDust