Advertisement
Combreal

PipedForks03.cpp

Jun 10th, 2018
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <iostream>
  7.  
  8. #define PIPE_READ 0
  9. #define PIPE_WRITE 1
  10.  
  11. std::string createChild(const char* bashCmd)
  12. {
  13.     int aStdinPipe[2];
  14.     int aStdoutPipe[2];
  15.     int nChild;
  16.     int nResult;
  17.     char buffer[4096];
  18.     std::string commandResult;
  19.     if(pipe(aStdinPipe) < 0)
  20.     {
  21.         exit(1);
  22.     }
  23.     if(pipe(aStdoutPipe) < 0)
  24.     {
  25.         close(aStdinPipe[PIPE_READ]);
  26.         close(aStdinPipe[PIPE_WRITE]);
  27.         exit(1);
  28.     }
  29.     nChild = fork();
  30.     if(0 == nChild)
  31.     {
  32.         if(dup2(aStdinPipe[PIPE_READ], STDIN_FILENO) == -1)//redirect stdin
  33.         {
  34.             exit(1);
  35.         }
  36.         if(dup2(aStdoutPipe[PIPE_WRITE], STDOUT_FILENO) == -1)
  37.         {
  38.             exit(1);
  39.         }
  40.         close(aStdinPipe[PIPE_READ]);
  41.         close(aStdinPipe[PIPE_WRITE]);
  42.         close(aStdoutPipe[PIPE_READ]);
  43.         close(aStdoutPipe[PIPE_WRITE]);
  44.         nResult = execl("/bin/bash", "bash", "-c", bashCmd, (char*)0);
  45.         exit(nResult);
  46.     }
  47.     else if(nChild > 0)
  48.     {
  49.         close(aStdinPipe[PIPE_READ]);
  50.         close(aStdoutPipe[PIPE_WRITE]);
  51.         memset(buffer, 0, sizeof(buffer));
  52.         read(aStdoutPipe[PIPE_READ], buffer, sizeof(buffer));
  53.         commandResult = buffer;
  54.         close(aStdinPipe[PIPE_WRITE]);
  55.         close(aStdoutPipe[PIPE_READ]);
  56.     } else
  57.     {
  58.         close(aStdinPipe[PIPE_READ]);
  59.         close(aStdinPipe[PIPE_WRITE]);
  60.         close(aStdoutPipe[PIPE_READ]);
  61.         close(aStdoutPipe[PIPE_WRITE]);
  62.     }
  63.     return commandResult;
  64. }
  65.  
  66. int main(void)
  67. {
  68.     std::cout<<"CommandReturns : "<<createChild("ls -hal")<<std::endl;//"echo \"test\""
  69.     std::cout<<"CommandBReturns : "<<createChild("echo \"test\"")<<std::endl;
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement