Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool execAndRedirect(std::string command, std::vector<std::string> args, std::string& output, int& status)
- {
- int error;
- int pipefd[2];
- int localStatus;
- if (pipe(pipefd) == -1)
- {
- error = errno;
- cerr << "Executing command '" << command << "' failed: " << strerror(error) << endl;
- return false;
- }
- pid_t pid = fork();
- if (pid == 0)
- {
- char** argsC;
- argsC = new char*[args.size() + 2];
- argsC[0] = new char[command.size() + 1];
- strncpy(argsC[0], command.c_str(), command.size());
- argsC[0][command.size()] = '\0';
- for (size_t count = 0; count < args.size(); count++)
- {
- argsC[count + 1] = new char[args[count].size() + 1];
- strncpy(argsC[count + 1], args[count].c_str(), args[count].size());
- argsC[count + 1][args[count].size()] = '\0';
- }
- argsC[args.size() + 1] = NULL;
- close(pipefd[0]);
- if (dup2(pipefd[1], STDOUT_FILENO) == -1)
- {
- error = errno;
- cerr << "Executing command '" << command << "' failed: " << strerror(error) << endl;
- exit(1);
- }
- if (dup2(pipefd[1], STDERR_FILENO) == -1)
- {
- error = errno;
- cerr << "Executing command '" << command << "' failed: " << strerror(error) << endl;
- exit(1);
- }
- close(pipefd[1]);
- if (execvp(command.c_str(), argsC) == -1)
- {
- error = errno;
- cerr << "Executing command '" << command << "' failed: " << strerror(error) << endl;
- exit(1);
- }
- }
- else if (pid > 0)
- {
- size_t BUFFER_SIZE = 1024;
- char buffer[BUFFER_SIZE + 1];
- close(pipefd[1]);
- ostringstream oss;
- ssize_t num_b;
- while ((num_b = read(pipefd[0], buffer, BUFFER_SIZE)) != 0)
- {
- buffer[num_b] = '\0';
- oss << buffer;
- }
- output = oss.str();
- waitpid(pid, &localStatus, 0);
- close(pipefd[0]);
- }
- else
- {
- error = errno;
- cerr << "Executing command '" << command << "' failed: " << strerror(error) << endl;
- return false;
- }
- if(WIFEXITED(localStatus))
- {
- status = WEXITSTATUS(localStatus);
- DateTime current = DateTime::now();
- if(status == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- error = errno;
- cerr << "Executing command '" << command << "' failed: child didn't terminate normally" << endl;
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement