I’m doing a course in Operating Systems and we’re supposed to learn how to use pipes to transfer data between processes.
We were given this simple piece of code which demonstrates how to use pipes,but I’m having difficulty understanding it.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
main()
{
int pipefd [2], n;
char buff[100] ;
if( pipe( pipefd) < 0)
{
printf("can not create pipe \n");
}
printf("read fd = %d, write fd = %d \n", pipefd[0], pipefd[1]);
if ( write (pipefd[1],"hello world\n", 12)!= 12)
{
printf("pipe write error \n");
}
if( ( n = read ( pipefd[0] , buff, sizeof ( buff) ) ) <= 0 )
{
printf("pipe read error \n");
}
write ( 1, buff, n ) ;
exit (0);
}
What does the write function do? It seems to send data to the pipe and also print it to the screen (at least it seems like the second time the write function is called it does this).
Does anyone have any suggestions of good websites for learning about topics such as this, FIFO, signals, other basic linux commands used in C?
The function creates a pipe and stores its endpoing file descriptors in
pipefd[0]andpipefd[1]. Anything you write to one end can be read from the other and vice versa. The firstwrite()call writes “hello world” topipefd[1], and theread()call reads that same data frompipefd[0]. Then, the secondwrite()call writes that data to file descriptor1, which isSTDOUTby default, which is why you see it on the screen.Pipes can be confusing at first. As you read / write more code that use them, they’ll become much easier to understand. I recommend W. Richard Stevens Advanced Programming in the UNIX Environment as a good book to understand them. As I recall, it has good code examples.