Unix Piping using Fork and Dup
- by Jacob
Lets say within my program I want to execute two child processes, one to to execute a "ls -al" command and then pipe that into "wc" command and display the output on the terminal. How can I do this using pipe file descriptors so far the code I have written: An example would be greatly helpful
int main(int argc, char *argv[]) {
int pipefd[2]
pipe(pipefd2);
if ((fork()) == 0) {
dup2(pipefd2[1],STDOUT_FILENO);
close(pipefd2[0]);
close(pipefd2[1]);
execl("ls", "ls","-al", NULL);
exit(EXIT_FAILURE);
}
if ((fork()) == 0){
dup2(pipefd2[0],STDIN_FILENO);
close(pipefd2[0]);
close(pipefd2[1]);
execl("/usr/bin/wc","wc",NULL);
exit(EXIT_FAILURE);
}
close(pipefd[0]);
close(pipefd[1]);
close(pipefd2[0]);
close(pipefd2[1]);
}