codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <iostream> using namespace std; void echo(int fd[2]); void grep(int fd[2]); int main() { int fd[2]; if (pipe(fd) == -1) { perror("pipe"); exit(1); } echo(fd); grep(fd); sleep(2); return 0; } void echo (int fd[2]) { char *echo = "echo"; char *argsE[] = { "echo", "12345\nabcd\n54321", NULL }; pid_t fork1 = fork(); if (fork1 == 0) { cout << "Echo PID: " << getpid() << endl; dup2(fd[1], 1); close(fd[1]); close(fd[0]); execvp(echo, argsE); cerr << "Error during echo" << endl; exit( -1 ); } else { close(fd[0]); close(fd[1]); int status1 = 0; waitpid(fork1, &status1, 0); if (WIFEXITED(status1)) cout << "Echo Exited: " << WEXITSTATUS(status1) << endl; } } void grep (int fd[2]) { char *grep = "grep"; char *argsG[] = { "grep", "1", NULL }; pid_t fork2 = fork(); if (fork2 == 0) { cout << "Grep PID: " << getpid() << endl; dup2(fd[0], 0); close(fd[1]); close(fd[0]); execvp(grep, argsG); cerr << "Error during grep" << endl; exit( -1 ); } else { close(fd[0]); close(fd[1]); int status2 = 0; cout << "Before wait" << endl; waitpid(fork2, &status2, 0); cout << "After wait" << endl; if (WIFEXITED(status2)) cout << "Grep Exited: " << WEXITSTATUS(status2) << endl; } }
Private
[
?
]
Run code
Submit