naraku9333

Untitled

May 3rd, 2014
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. void setup_pipe(int fd[2], int used, int unused);
  2.  
  3. int main()
  4. {
  5.     while (true)
  6.     {    
  7.         std::string com1, com2;
  8.         std::cout << "Enter command 1 (incl. args) or quit: ";
  9.         std::getline(std::cin, com1);
  10.         if(com1 == "quit") return EXIT_SUCCESS;
  11.  
  12.         std::cout << "Enter command 2 (incl. args) : ";
  13.         std::getline(std::cin, com2);
  14.  
  15.         int fd[2];
  16.         if(pipe(fd) == -1)
  17.         {
  18.             perror("pipe");
  19.             exit(EXIT_FAILURE);
  20.         }
  21.  
  22.         pid_t pid;
  23.         if((pid = fork()) == -1)
  24.         {
  25.             perror("fork");
  26.             exit(EXIT_FAILURE);            
  27.         }
  28.  
  29.         if(pid == 0)//child 1
  30.         {
  31.             setup_pipe(fd, 1, 0);
  32.             //std::cout << "child running com1 " << com1 <<std::endl;//DBG
  33.             if(execlp(com1.c_str(), com1.c_str(), nullptr) == -1)
  34.             {
  35.                 perror("execlp");
  36.                 exit(EXIT_FAILURE);
  37.             }
  38.         }
  39.         else//parent
  40.         {
  41.             setup_pipe(fd, 0, 1);
  42.             if((pid = fork()) == -1)
  43.             {
  44.                 perror("fork");
  45.                 exit(EXIT_FAILURE);            
  46.             }
  47.  
  48.             if(pid == 0)//child 2
  49.             {
  50.                 //setup_pipe(fd, 0, 1);
  51.                 //std::cout << "child running com2 " << com2 <<std::endl;//DBG
  52.                 if(execlp(com2.c_str(), com2.c_str(), nullptr) == -1)
  53.                 {
  54.                     perror("execlp");
  55.                     exit(EXIT_FAILURE);
  56.                 }
  57.             }
  58.             else//parent
  59.             {
  60.                 wait(NULL);
  61.                 wait(NULL);
  62.               //  std::cout << "parent done" <<std::endl;//DBG
  63.             }
  64.         }
  65.         std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');        
  66.  
  67.     }
  68. }
  69.  
  70. void setup_pipe(int fd[2], int used, int unused)
  71. {
  72.     close(fd[unused]);
  73.     close(used);
  74.     dup(fd[used]);
  75.     close(fd[used]);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment