Using pipes in Linux with C
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 i开发者_如何学Pythont 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 program creates a pipe via the pipe(2) call. The pipe has a file descriptor open for reading (pipefd[0]
) and one open for writing (pipefd[1]
). The program first writes "hello world\n" to the write end of the pipe and then reads the message out of the read end of the pipe. The message is then written out to the console (stdout) via the write(2) call to file descriptor 1.
Beej's Guide to Unix Interprocess Communication provides some good information on Unix/Linux IPC. You will often find references to his other guide, Beej's Guide to Network Programming.
I found Understanding UNIX/LINUX Programming: A Guide to Theory and Practice by Bruce Molay to be an excellent book on Unix/Linux system programming.
The first argument to write()
is the file descriptor to write to.
In the first call, the code is writing to one end of the pipe (pipefd[1]
). In the second call, it is writing to file descriptor 1, which in POSIX-compliant systems is always standard output (the console). File descriptor 2 is standard error, for what it's worth.
The function creates a pipe and stores its endpoing file descriptors in pipefd[0]
and pipefd[1]
. Anything you write to one end can be read from the other and vice versa. The first write()
call writes "hello world" to pipefd[1]
, and the read()
call reads that same data from pipefd[0]
. Then, the second write()
call writes that data to file descriptor 1
, which is STDOUT
by 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.
精彩评论