#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys /types.h> #include <limits.h> #include <string.h> #include <sys/wait.h># include <error.h> #define DEF_PAGER "/bin/more" //defining handler functions #define maxline 4096 //line maximum number of characters Int main (int argc, char *argv[]) { int n; int fd[2]; pid_t pid; char *pager, *argv0; char line[MAXLINE]; FILE *fp; if (argc != 2 ) //If the parameter is incorrect { printf ("Please enter the correct command: <pathname>\n"); exit (1); } if ((Fp = fopen (argv[1], "R")) == NULL) //If read-onlyError opening argv[1] { printf ("Cannot open file%s", argv[1]); Exit (1); } if (pipe (FD) < 0) //Create pipeline failure { &NBSP;&NBSP;&NBSP;PRINTF ("Create pipe failed \ n"); exit (0); } if (PID = fork ()) < 0) //Create child process failed { printf (" Create child process failed \ n "); exit (0); } else if (pid > 0) { //Parent Process close (Fd[0]); //Close Read file descriptor //Argv[1] sent through the pipeline while (fgets (LINE,&NBSP;MAXLINE,&NBSP;FP) != null) { n = strlen (line); if (Write (fd[1], line, n) != n) { printf ("Write pipeline failed \ n"); exit (1); } } if (Ferror (FP)) //If the file descriptor is faulted { printf ("fgets Failure \ \ "); exit (1); } close (Fd[1]); // if (Waitpid (pid, NULL, 0) < 0) { printf ("Waitpid failure \ n"); exit (1); } exit ( 0); } else //Sub-process { close (fd[1]); if (fd[ 0] != stdin_fileno) { if (Dup2 (fd[0], stdin_fileno) != stdin_fileno) { printf ("Dup2 to standard input failed \ n"); exit (1); } close (Fd[0]); /* don ' Parameters of the T need this after dup2 */ } //exec function if ((pager = getenv ("pager") == null) { pager = DEF_PAGER; } if ((ARGV0&NBSP;=&NBSP;STRRCHR (pager, '/')) != null) { argv0++; } else { argv0 = pager; } if (Execl (pager, argv0, (char *) 0) < 0) { printf ("Call Execl failed%s", pager); exit (1); } } exit (0);}
This article is from the "10628473" blog, please be sure to keep this source http://10638473.blog.51cto.com/10628473/1983130
Practical application of [Linux pipelines and IPC] Pipelines 2