Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void setup_pipe(int fd[2], int used, int unused);
- int main()
- {
- while (true)
- {
- std::string com1, com2;
- std::cout << "Enter command 1 (incl. args) or quit: ";
- std::getline(std::cin, com1);
- if(com1 == "quit") return EXIT_SUCCESS;
- std::cout << "Enter command 2 (incl. args) : ";
- std::getline(std::cin, com2);
- int fd[2];
- if(pipe(fd) == -1)
- {
- perror("pipe");
- exit(EXIT_FAILURE);
- }
- pid_t pid;
- if((pid = fork()) == -1)
- {
- perror("fork");
- exit(EXIT_FAILURE);
- }
- if(pid == 0)//child 1
- {
- setup_pipe(fd, 1, 0);
- //std::cout << "child running com1 " << com1 <<std::endl;//DBG
- if(execlp(com1.c_str(), com1.c_str(), nullptr) == -1)
- {
- perror("execlp");
- exit(EXIT_FAILURE);
- }
- }
- else//parent
- {
- setup_pipe(fd, 0, 1);
- if((pid = fork()) == -1)
- {
- perror("fork");
- exit(EXIT_FAILURE);
- }
- if(pid == 0)//child 2
- {
- //setup_pipe(fd, 0, 1);
- //std::cout << "child running com2 " << com2 <<std::endl;//DBG
- if(execlp(com2.c_str(), com2.c_str(), nullptr) == -1)
- {
- perror("execlp");
- exit(EXIT_FAILURE);
- }
- }
- else//parent
- {
- wait(NULL);
- wait(NULL);
- // std::cout << "parent done" <<std::endl;//DBG
- }
- }
- std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
- }
- }
- void setup_pipe(int fd[2], int used, int unused)
- {
- close(fd[unused]);
- close(used);
- dup(fd[used]);
- close(fd[used]);
- }
Advertisement
Add Comment
Please, Sign In to add comment