Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <iostream>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <vector>
- #include <string>
- using namespace std;
- void Exec(vector<string>& command)
- {
- int size = command.size();
- char** args = new char* [size + 1];
- args[size] = NULL;
- for (int i = 0; i < size; i++)
- args[i] = (char*)command[i].c_str();
- execvp(args[0], args);
- }
- vector< vector<string> > ParseCommands(char* buffer, int size)
- {
- vector< vector<string> > commands;
- vector<string> empty;
- commands.push_back(empty);
- commands[0].push_back("");
- int k = 0, l = 0;
- for (int i = 0; i < size; i++)
- {
- if (buffer[i] == ' ')
- {
- if (commands[k][l].size() > 0)
- {
- commands[k].push_back("");
- l++;
- }
- }
- else if (buffer[i] == '|')
- {
- if (commands[k][l].size() <= 0)
- commands[k].pop_back();
- commands.push_back(empty);
- k++;
- commands[k].push_back("");
- l = 0;
- }
- else
- commands[k][l] += buffer[i];
- }
- return commands;
- }
- int main(int argc, char** argv)
- {
- char buffer[1024];
- int size = read(STDIN_FILENO, buffer, 1024);
- vector< vector<string> > commands = ParseCommands(buffer, size);
- int k = 0;
- while (true)
- {
- if (k >= commands.size() - 1)
- {
- int fd = open("/home/box/result.out", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
- close(STDOUT_FILENO);
- dup2(fd, STDOUT_FILENO);
- close(fd);
- Exec(commands[k]);
- break;
- }
- int pfd[2];
- pipe(pfd);
- if ((pid = fork()))
- {
- close(STDOUT_FILENO);
- dup2(pfd[1], STDOUT_FILENO);
- close(pfd[1]);
- close(pfd[0]);
- waitpid(pid, NULL, 0);
- Exec(commands[k]);
- break;
- }
- else
- {
- close(STDIN_FILENO);
- dup2(pfd[0], STDIN_FILENO);
- close(pfd[1]);
- close(pfd[0]);
- k++;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement