/*This program shows how to create and use named pipes with C on a*/ /*Unix system. It also shows how to pipe commands within a C program*/ /*In this program, a child process is broken off from the aprent process*/ /*The parent executes a Unix command ("ls" in this case),a nd the parent*/ /*fredirects the outputto the child process, which processes it with */ /*another command ("grep"). */ #include #include #include int main() { int fd, ret; pid_t pid; /*Ford the program here into a parent and child process*/ pid = fork(); /*The mkfifo call actually creates the named pipe, which*/ /*resides as a file in the directory where the program is lcoated*/ ret = mkfifo("MyFirstCPipe", 0666); if (pid < 0) { printf("fork error\n"); } /***************Parent*****/ else if (pid > 0) { /*Below, the parent opens the file. Obviously you can name the*/ /*pipe anything you want*/ fd = open("MyFirstCPipe", O_RDWR); /*The line below closes standard output to the screen...*/ close(1); /*Instead the outpout is directed to the named pipe*/ dup(fd); /*Executes a Unix command, the result of which is sent to the child pogram*/ execl("/bin/ls", "/bin/ls", "-l", "-a", (char *) 0); } /**************Child****************/ else if (pid == 0) { /*The child closes standardinput*/ close(0); /*and instead eceivesthe input from the named pipe...*/ fd = open("MyFirstCPipe", O_RDONLY); /*The input is processed by another Unix program*/ /*The results of which are shown on the screen...*/ execl("/bin/grep", "/bin/grep", "NamedPipe.c", (char *) 0); } }