Here's my attempt to try to understand how to do correct piping between two child processes. I'm simply trying to pass the output of one Linux command to another (ls to cat) and have the program return successfully. However, I'm guessing that the second child that is forked is getting stuck and the parent is forever waiting on this child. I have been fiddling with this code for a long time trying to find out why it's getting stuck. I'm kind of a noob when it comes to C system programming, but I am trying to learn.
Does anybody have any idea why the program does not exit, but hangs on cat?
Any help would be greatly appreciated.
Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char *a[2] = {"/bin/ls", NULL};
char *b[2] = {"/bin/cat", NULL};
char *envp[2] = {getenv("PATH"), NULL};
int fd[2], status;
pipe(fd);
int old_std_out = dup(1);
int old_std_in = dup(0);
dup2(fd[1], 1);
int pid = fork();
switch(pid)
{
case -1:
perror("Forkscrew");
exit(1);
break;
case 0:
execve(a[0], a, envp);
exit(0);
break;
default:
waitpid(-1, &status, 0);
dup2(old_std_out, 1);
break;
}
dup2(fd[0], 0);
pid = fork();
switch(pid)
{
case -1:
perror("Forkscrew");
exit(1);
break;
case 0:
execve(b[0], b, envp);
exit(0);
break;
default:
waitpid(-1, &status, 0);
dup2(old_std_in, 0);
break;
}
printf("\n");
return 0;
}