naraku9333

Untitled

Mar 24th, 2015
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. void execute_cmds(int fd[2], const std::vector<std::string>& commands)
  2. {
  3.     for(std::size_t i = 0; i < commands.size(); ++i)
  4.     {
  5.         auto pid = fork();
  6.        
  7.         auto args = split_to_cstr(commands[i]);
  8.         if(pid == 0)
  9.         {
  10.             if(i == 0)//first command
  11.             {
  12.                 if(commands.size() > 1)
  13.                 {
  14.                     close(fd[0]);
  15.                     dup2(fd[1], 1);
  16.                     //close(fd[1]);
  17.                 }
  18.             }
  19.             else if(i == commands.size() - 1)//last command
  20.             {
  21.                 close(fd[1]);
  22.                 dup2(fd[0], 0);
  23.                 //close(fd[0]);
  24.             }
  25.             else//inner commands
  26.             {
  27.                 dup2(fd[0], 0);
  28.                 //close(fd[0]);
  29.                 dup2(fd[1], 1);
  30.                 //close(fd[1]);
  31.             }
  32.             if(execvp(args[0], &args[0]) < 0)
  33.             {
  34.                 std::perror("execvp");
  35.                 exit(EXIT_FAILURE);
  36.             }          
  37.         }
  38.         else if(pid < 0)
  39.         {
  40.             std::perror("fork");
  41.             exit(EXIT_FAILURE);
  42.         }      
  43.     }
  44. }
  45.  
  46. int main()
  47. {
  48.     std::string prompt("microshell>"),
  49.                 input;
  50.     int fd[2];
  51.  
  52.     while(std::cout << prompt && std::getline(std::cin, input))
  53.     {
  54.         if(pipe(fd) < 0)
  55.         {
  56.             std::perror("pipe");
  57.             exit(EXIT_FAILURE);
  58.         }
  59.  
  60.         std::vector<std::string> commands(get_cmds(input, "||"));
  61.  
  62.         execute_cmds(fd, commands);
  63.  
  64.         close(fd[0]);
  65.         close(fd[1]);
  66.  
  67.         //wait for children to finish
  68.         int pid, status;
  69.         while ((pid = wait(&status)) != -1) ;
  70.             //std::cerr <<  "process " << pid << " exits with " << WEXITSTATUS(status) << std::endl;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment