/* * COSC 6377 Sample Code #4 - How to execute filter - a pipe example * * This program is an example to demonstrate the use of pipe. * There are two processes in this program, the child process * calls "execve" to execute an external program; the father * process read input from stdin, copy it to the child process * via a pipe, read output of the child process via another * pipe and print out output of the child process to stdout. * Actually, this program does nothing, just an encapsulatiaon * of the child process. For more information, refer to pipe (2), * "man -s2 pipe". * * To compile: g++ -o pipe_test pipe.cc * To test: pipe_test /bin/cat * * -- C. T. */ #include #include #include #include int main (int argc, char **argv) { int childpid, pipe1[2], pipe2[2]; char buf[256]; if (argc != 2) { printf ("Usuage: %s command\n", argv[0]); exit (1); } // create 2 pipe, data flow: // father process =pipe1=> child process =pipe2=> father process if (pipe (pipe1) < 0 || pipe (pipe2) < 0) { perror ("pipe error"); return 1; } if ((childpid = fork ()) < 0) { perror ("fork error"); return 1; } else if (childpid > 0) // father { close (pipe1[0]); // father don't need these fds. close (pipe2[1]); while (!feof (stdin)) { fgets (buf, 255, stdin); // read from stdin buf[strlen(buf)-1] = 0; strcat (buf, " -- Garbled by father\n"); // garble the string write (pipe1[1], buf, strlen (buf)); // write to child read (pipe2[0], buf, 255); // read from child - should get garbled string puts (buf); // write to stdout } close (pipe1[1]); close (pipe2[0]); } else // child { char *chd_argv[2]; close (pipe1[1]); // child don't need these fds. close (pipe2[0]); close (0); dup (pipe1[0]); // redirect child's stdin to pipe1 close (1); dup (pipe2[1]); // redirect child's stdout to pipe2 chd_argv[0]=argv[1]; chd_argv[1]=0; // if you use execve, you have to fill in chd_argv to // supply the argumets for the command. // execve(argv[1], chd_argv, NULL); // exececute argv[1] // if you use system, argument is parsed by shell // automatically. system(argv[1]); close (pipe1[0]); close (pipe2[1]); } return 0; }