Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <string.h>
- #include <iostream>
- #include <sys/wait.h>
- #define PIPE_READ 0
- #define PIPE_WRITE 1
- std::string createChild(const char* bashCmd)
- {
- int aStdinPipe[2];
- int aStdoutPipe[2];
- int nChild;
- int nResult;
- char buffer[4096];
- char ch;
- std::string commandResult, cmdRec;
- if(pipe(aStdinPipe) < 0)
- {
- exit(1);
- }
- if(pipe(aStdoutPipe) < 0)
- {
- close(aStdinPipe[PIPE_READ]);
- close(aStdinPipe[PIPE_WRITE]);
- exit(1);
- }
- nChild = fork();
- if(0 == nChild)
- {
- if(dup2(aStdinPipe[PIPE_READ], STDIN_FILENO) == -1)//redirect stdin
- {
- exit(1);
- }
- if(dup2(aStdoutPipe[PIPE_WRITE], STDOUT_FILENO) == -1)
- {
- exit(1);
- }
- close(aStdinPipe[PIPE_READ]);
- close(aStdinPipe[PIPE_WRITE]);
- close(aStdoutPipe[PIPE_READ]);
- close(aStdoutPipe[PIPE_WRITE]);
- nResult = execl("/bin/bash", "bash", "-c", bashCmd, (char*)0);
- exit(nResult);
- }
- else if(nChild > 0)
- {
- close(aStdinPipe[PIPE_READ]);
- close(aStdoutPipe[PIPE_WRITE]);
- memset(buffer, 0, sizeof(buffer));
- //read(aStdoutPipe[PIPE_READ], buffer, sizeof(buffer));
- while(read(aStdoutPipe[PIPE_READ], &ch, 1) > 0)
- {
- if(ch != 0)
- cmdRec.push_back(ch);
- else
- {
- cmdRec.append(" ");
- }
- }
- //commandResult = buffer;
- commandResult = cmdRec;
- wait(NULL);//wait for child proc
- close(aStdinPipe[PIPE_WRITE]);
- close(aStdoutPipe[PIPE_READ]);
- } else
- {
- close(aStdinPipe[PIPE_READ]);
- close(aStdinPipe[PIPE_WRITE]);
- close(aStdoutPipe[PIPE_READ]);
- close(aStdoutPipe[PIPE_WRITE]);
- std::cout<<"ERROR - couldn't read from pipe"<<std::endl;
- }
- return commandResult;
- }
- int main(void)
- {
- std::cout<<"CommandBReturns : "<<createChild("echo \"test\"")<<std::endl;
- //std::cout<<"CommandBReturns : "<<createChild("/usr/local/bin/brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb")<<std::endl;
- return 0;
- }
- //g++ -g -o testProc main.cpp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement