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
0and1in your diagram and you got what I’ll describe below.From the Mac OS X man page:
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.
pipeand get the two file descriptors.forkto 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.