Pipes
Pipes are used to allow one or more processes
to have information "flow" between them. The most
common example of this is with the shell.
$ ls | wc -lAs weve seen the std-out from the left side (ls) is connected to the std-in on the right side (wc -l).As far the each program is concerned, it is reading or writing as it normally does. Both processes are running concurrently.
#include <unistd.h> int pipe(int fd[2]);Returns 2 file descriptors in the fd array.
#include <stdio.h>
/* The index of the "read" end of the pipe */
#define READ 0
/* The index of the "write" end of the pipe */
#define WRITE 1
char *phrase = "Stuff this in your pipe and smoke it";
main () {
int fd[2], bytesRead;
char message [100]; /* Parent process message buffer */
pipe ( fd ); /*Create an unnamed pipe*/
if ( fork ( ) == 0 ) {
/* Child Writer */
close (fd[READ]); /* Close unused end*/
write (fd[WRITE], phrase, strlen ( phrase) +1); /* include NULL*/
close (fd[WRITE]); /* Close used end*/
printf("Child: Wrote '%s' to pipe!\n", phrase);
} else {
/* Parent Reader */
close (fd[WRITE]); /* Close unused end*/
bytesRead = read ( fd[READ], message, 100);
printf ( "Parent: Read %d bytes from pipe: %s\n", bytesRead, message);
close ( fd[READ]); /* Close used end */
}
}
$ mknod mypipe pFrom a C program
mknod ( "mypipe", SIFIFO, 0 );Either way you create it, this will result in a special file being created on the filesystem.
$ ls -l mypipe prw-rr-- 1 srs users 0 Nov 6 22:28 mypipeOnce a named pipe is created, processes can open(), read() and write() them just like any other file. Unless you specify O_NONBLOCK, or O_NDELAY, on the open:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
char * phrase = "Stuff this in your pipe and smoke it";
int main () {
int fd1;
fd1 = open ( "mypipe", O_WRONLY );
write (fd1, phrase, strlen ( phrase)+1 );
close (fd1);
}
Reader
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main () {
int fd1;
char buf [100];
fd1 = open ( "mypipe", O_RDONLY );
read ( fd1, buf, 100 );
printf ( "%s\n", buf );
close (fd1);
}
NOTE 1: This document was snarfed and reformatted from http://www.cs.fredonia.edu/~zubairi/s2k2/csit431/pipes.html.
Sample code was slightly improved. fgm
NOTE 2: This help document was taken from academic website
and it also contains example source code from a UNIX programming
book