Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void execute_cmds(int fd[2], const std::vector<std::string>& commands)
- {
- for(std::size_t i = 0; i < commands.size(); ++i)
- {
- auto pid = fork();
- auto args = split_to_cstr(commands[i]);
- if(pid == 0)
- {
- if(i == 0)//first command
- {
- if(commands.size() > 1)
- {
- close(fd[0]);
- dup2(fd[1], 1);
- //close(fd[1]);
- }
- }
- else if(i == commands.size() - 1)//last command
- {
- close(fd[1]);
- dup2(fd[0], 0);
- //close(fd[0]);
- }
- else//inner commands
- {
- dup2(fd[0], 0);
- //close(fd[0]);
- dup2(fd[1], 1);
- //close(fd[1]);
- }
- if(execvp(args[0], &args[0]) < 0)
- {
- std::perror("execvp");
- exit(EXIT_FAILURE);
- }
- }
- else if(pid < 0)
- {
- std::perror("fork");
- exit(EXIT_FAILURE);
- }
- }
- }
- int main()
- {
- std::string prompt("microshell>"),
- input;
- int fd[2];
- while(std::cout << prompt && std::getline(std::cin, input))
- {
- if(pipe(fd) < 0)
- {
- std::perror("pipe");
- exit(EXIT_FAILURE);
- }
- std::vector<std::string> commands(get_cmds(input, "||"));
- execute_cmds(fd, commands);
- close(fd[0]);
- close(fd[1]);
- //wait for children to finish
- int pid, status;
- while ((pid = wait(&status)) != -1) ;
- //std::cerr << "process " << pid << " exits with " << WEXITSTATUS(status) << std::endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment