I've been trying to use the pipe() system call to create a shell that supports piping (with an arbitrary number of commands).
Unfortunately, I haven't had much luck using pipe(). After spending a few days looking at various online resources, I decided to put together an oversimplified program that has the same effect as executing ls | sort
to see if I could even get a pipe to work for two sibling, child processes. Here's the code:
#include <sys/wait.h>
#include <unistd.h>
void run(char *cmd) {
char *args[2];
args[0] = cmd;
args[1] = NULL;
execvp(cmd, args);
}
int main(void) {
int filedes[2];
pipe(filedes);
pid_t pid_a, pid_b;
if (!(pid_a = fork())) {
dup2(filedes[1], 1);
run("ls");
}
if (!(pid_b = fork())) {
dup2(filedes[0], 0);
run("sort");
}
waitpid(pid_a, NULL, 0);
waitpid(pid_b, NULL, 0);
return 0;
}
The pipe is created in the parent and I know that after the execvp() call, each child process inherits the file descriptors that pipe() creates in the parent. For the ls
process, I'm using dup2() to redirect its standard out (1) to the write-end of the pipe and for the sort
process, standard in (0) is being redirected to the read-end of the pipe.
Finally, I wait for both processes to finish before exiting.
My intuition tells me this should work, but it doesn't!
Any suggestions?