For the past few days I have been attempting to write my own shell implementation but I seem to have gotten stuck on getting pipes to work properly. I am able to parse a li
ok This is working for me. Hope this helps you:
/************************
function: void pipeCommand(char** cmd1, char** cmd2)
comment: This pipes the output of cmd1 into cmd2.
**************************/
void pipeCommand(char** cmd1, char** cmd2) {
int fds[2]; // file descriptors
pipe(fds);
// child process #1
if (fork() == 0) {
// Reassign stdin to fds[0] end of pipe.
dup2(fds[0], STDIN_FILENO);
close(fds[1]);
close(fds[0]);
// Execute the second command.
// child process #2
if (fork() == 0) {
// Reassign stdout to fds[1] end of pipe.
dup2(fds[1], STDOUT_FILENO);
close(fds[0]);
close(fds[1]);
// Execute the first command.
execvp(cmd1[0], cmd1);
}
wait(NULL);
execvp(cmd2[0], cmd2);
}
close(fds[1]);
close(fds[0]);
wait(NULL);
}