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?
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.
pipe
and get the two file descriptors.fork
to create the child.
fd[1]
) and leave the reading one open.fd[0]
) file descriptor and leave the writing one open.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With