Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdio.h>
- #include <cstdio>
- #include <fcntl.h>
- #include <iostream>
- #include <sys/wait.h>
- #include <vector>
- #include <sstream>
- using VS = std::vector<std::string>;
- using VVS = std::vector<VS>;
- using VChars = std::vector<const char*>;
- using VVChars= std::vector<VChars>;
- struct VectorCmd
- {
- VVS vCmds;
- VVChars cmd;
- VectorCmd(const std::string inp)
- {
- VS segPipes = split(inp, '|');
- for (unsigned i = 0; i < segPipes.size(); ++i)
- { vCmds.push_back(split(segPipes[i], ' ')); }
- for (unsigned i = 0; i <vCmds.size(); ++i)
- {
- VChars v;
- for (unsigned k = 0; k < vCmds[i].size(); ++k)
- {
- v.push_back(vCmds[i][k].c_str());
- }
- v.push_back((char*)NULL);
- cmd.push_back(v);
- }
- }
- VS split(const std::string &s, const char delimiter)
- {
- std::stringstream ss(s);
- std::string segment;
- VS lst;
- while(std::getline(ss, segment, delimiter))
- if (segment.size())
- lst.push_back(segment);
- return lst;
- }
- void print() {
- for (auto & v:cmd)
- {
- for(auto &s:v) if (s) std::cout << s<< " ";
- else std::cout << "NULL ";
- std::cout <<"|" << std::endl;
- }
- }
- };
- void closepfd(std::vector<int> &pfd)
- {
- for (unsigned i = 0; i < pfd.size(); ++i)
- close(pfd[i]);
- }
- int main()
- {
- std::string inp;
- std::getline(std::cin, inp);
- VectorCmd vc(inp);
- std::vector<int> pfd (vc.cmd.size()*2);
- for (int i = 0; i < vc.cmd.size(); ++i)
- pipe(&pfd[2*i]);
- for (unsigned i = 0; i < vc.cmd.size(); ++i)
- {
- // pipe(&pfd[2*i]);
- int pid = fork();
- if (pid == 0) {
- if (i != 0) {
- dup2(pfd[i*2-2], STDIN_FILENO);
- }
- dup2(pfd[i*2+1], STDOUT_FILENO);
- closepfd(pfd);
- const std::vector<const char*> &pcmd = vc.cmd[i];
- // std::cerr <<i << std::endl;
- execvp(pcmd[0], const_cast<char*const*>(pcmd.data()));
- }
- else
- {
- int status;
- if (i == vc.cmd.size()-1) {
- dup2(pfd[i*2], STDIN_FILENO);
- closepfd(pfd);
- freopen("/home/box/result.out", "w", stdout);
- std::cout << std::cin.rdbuf();
- }
- else
- {
- //closepfd(pfd);
- // waitpid(pid, &status, 0);
- }
- //aitpid(pid, &status, 0);
- }
- }
- wait(0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement