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>
- #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];
- std::string commandResult;
- 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));
- commandResult = buffer;
- 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]);
- }
- return commandResult;
- }
- int main(void)
- {
- std::cout<<"CommandReturns : "<<createChild("ls -hal")<<std::endl;//"echo \"test\""
- std::cout<<"CommandBReturns : "<<createChild("echo \"test\"")<<std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement