Hello all, I am trying to learn more about programming Unix pipes in C.
I have created a pipe that does od -bc < myfile | head
Now, I am trying to create od -bc < myfile | head | wc
Here is my code, and I know I might be off, thats why I am here so I can get some clarification.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/file.h>
int main(int argc, char *argv[]) {
int i, filefd, pipefd[2], od_pid, head_pid, pid, wc_pid;
for (i = 1; i < argc; i++) {
filefd = open(argv, O_RDONLY);
if (filefd < 0){
printf("%s could not be opened\n", argv);
continue;
}
dup2(filefd, STDIN_FILENO);
close(filefd);
pipe(pipefd);
if ((od_pid = fork()) == 0) {
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execl("/usr/bin/od", "od", "-bc", NULL);
exit(EXIT_FAILURE);
}
if ((head_pid = fork()) == 0) {
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execl("/usr/bin/head","head", NULL);
exit(EXIT_FAILURE);
}
if ((wc_pid = fork()) == 0) {
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execl("/usr/bin/wc","wc", NULL);
exit(EXIT_FAILURE);
}
close(pipefd[0]);
close(pipefd[1]);
do {
pid = wait(NULL);
if (pid == od_pid)
od_pid = 0;
if (pid == head_pid)
head_pid = 0;
if (pid == wc_pid)
head_pid = 0;
} while ((od_pid != 0 || head_pid != 0 || wc_pid !=0) && pid != -1);
} /* end of for loop*/
exit(EXIT_SUCCESS);
}
Any direction would be appreciated. Cheers.
---------- Post updated at 11:53 PM ---------- Previous update was at 11:01 PM ----------
oh ok...figured it out. I had to create another pipe to take the input from "head".
Cheers!