Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using std::cout;
- using std::cerr;
- using std::endl;
- int MAXLINE = 9000;
- //ps -A | grep argv[1] | wc -l
- int main(int argc, const char* argv[]) {
- int pid, char_count, ps_pipes[2], wc_pipes[2];
- char line[MAXLINE];
- if (argc != 2) {
- cerr << "Error: invalid number of arguments (" << argc << "). Expecting 2" << endl;
- return 1;
- }
- //The commands are forked in reverse order wc -> grep -> ps
- //create the pipe
- if (pipe(ps_pipes) < 0 && pipe(wc_pipes) < 0) {
- cerr << "Pipe error" << endl;
- return -1;
- }
- pid = fork();//child forked for grep
- if (pid < 0) {
- cerr << "First Fork error" << endl;
- return -1;
- }
- //Parent (wc -l)
- if (pid > 0) {
- wait();//Have to wait for grep to finish
- close(wc_pipes[1]);//close the write pipe, this should write to stdout
- dup2(wc_pipes[0], 0);//set the stdin of the process to the read pipe
- execlp("wc", "wc", "-l", (char*)0);//Replace the process
- } else { //Child (grep argv[1])
- pid = fork();//child forked for ps
- if (pid < 0) {
- cerr << "Second Fork error" << endl;
- return -1;
- }
- //In main child (grep argv[1])
- if (pid > 0) { //in parent (grep argv[1])
- wait();
- close(ps_pipes[1]);//close the write pipe from ps. grep will write to wc_pipes
- close(wc_pipes[0]);
- dup2(ps_pipes[0], 0);//set the stdin of the process to the read pipe
- dup2(wc_pipes[1], 1);//set the stdout of the process to go to wc
- execlp("grep", "grep", argv[1], (char*)0);//Replace the process
- } else {//Grand-Child (ps -A)
- close(ps_pipes[0]);//close the read pipe. ps won't be reading
- dup2(ps_pipes[1], 1);//set the stdout of the process to go to grep
- execlp("ps", "ps", "-A", (char*)0);//Replace the process
- }
- }
- exit(0);
- }
Add Comment
Please, Sign In to add comment