Advertisement
lubaochuan

Untitled

Feb 7th, 2012
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.22 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5.  
  6. int run_command(char** arg_list, int rd, int wd) {
  7.   pid_t child_pid;
  8.  
  9.   /* Duplicate this process. */
  10.   child_pid = fork();
  11.  
  12.   if (child_pid != 0){
  13.     /* This is the parent process. */
  14.     return child_pid;
  15.   }else {
  16.     if (rd != STDIN_FILENO){
  17.       if(dup2(rd, STDIN_FILENO) != STDIN_FILENO){
  18.     fprintf(stderr, "Error: failed to redirect standard input\n");
  19.         return -1;
  20.       }
  21.     }
  22.  
  23.     if (wd != STDOUT_FILENO){
  24.       printf("redirect stdout to %d.", wd);
  25.       if(dup2(wd, STDOUT_FILENO) != STDOUT_FILENO){
  26.         fprintf(stderr, "Error: failed to redirect standard output\n");
  27.         return -1;
  28.       }
  29.     }
  30.     /* Now execute PROGRAM, searching for it in the path.  */
  31.     execvp (arg_list[0], arg_list);
  32.     /* The execvp  function returns only if an error occurs.  */
  33.     fprintf (stderr,  "an error occurred in execvp\n");
  34.     abort ();
  35.   }
  36. }
  37.  
  38. int main () {
  39.   /*  The argument list to pass to the "ls" command.  */
  40.   char* arg_list1[] = {
  41.     "ls",     /* argv[0], the name of the program.  */
  42.     "-l",
  43.     NULL      /* The argument list must end with a NULL.  */
  44.   };
  45.  
  46.   char* arg_list2[] = {
  47.     "wc",     /* argv[0], the name of the program.  */
  48.     "-l",
  49.     NULL      /* The argument list must end with a NULL.  */
  50.   };
  51.  
  52.   char* arg_list3[] = {
  53.     "wc",     /* argv[0], the name of the program.  */
  54.     "-l",
  55.     NULL      /* The argument list must end with a NULL.  */
  56.   };
  57.  
  58.   int rd;
  59.   int wd;
  60.   int fds[2];
  61.   if (pipe(fds) != 0) {
  62.     fprintf(stderr, "Error: unable to pipe command '%s'\n", arg_list1[0]);
  63.     return -1;
  64.   }  
  65.   rd = STDIN_FILENO;
  66.   wd = fds[1];
  67.  
  68.   // run the first command
  69.   run_command(arg_list1, rd, wd);
  70.   close(wd);
  71.  
  72.   // run the second command
  73.   rd = fds[0];
  74.   if (pipe(fds) != 0) {
  75.     fprintf(stderr, "Error: unable to pipe command '%s'\n", arg_list2[0]);
  76.     return -1;
  77.   }
  78.   wd = fds[1];
  79.  
  80.   run_command(arg_list2, rd, wd);
  81.   close(wd);
  82.  
  83.   // run the third command
  84.   rd = fds[0];
  85.   wd = STDOUT_FILENO;
  86.  
  87.   run_command(arg_list3, rd, wd);
  88.   close(wd);
  89.   fprintf (stderr, "done with main program\n");
  90.   return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement