I'm learning C and currently i'm trying to make a shell. Anyway i made a test program to figure out how multiple pipes work. I changed the program to use a single pipe command and it prints the result fine. Then i changed it back to this code where that runs it for 2 pipes, but i always get output 0. I really have no clue why the output is 0. Can you help me?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
int main(int argc, char * argv[])
{
int j;
pid_t pid;
int pfd[4];
char * ls[] = {"ls","-l",0};
char * sort[] = {"sort","-u",0};
char * wc[] = {"wc","-l",0};
int fd = open("outputfolder.txt", O_WRONLY | O_CREAT | O_APPEND);
for ( int i = 0; i < 4; i++ )
{
if ( pipe(pfd + i*2) < 0 )
{
perror("pipe\n");
exit(EXIT_FAILURE);
}
}
for ( int i = 0; i <= 2; i ++ )
{
if ( i == 2 )
{
pid = fork();
if ( pid == 0 )
{
if ( dup2(pfd[(i-1)*2],0) < 0 )
{
perror("dup2\n");
exit(EXIT_FAILURE);
}
if ( dup2(fd,1) < 0 )
{
perror("dup2\n");
exit(EXIT_FAILURE);
}
for (j = 0; j < 4; j++ )
{
close(pfd[j]);
}
if ( execvp(wc[0],wc) < 0 )
{
perror("execvpwc\n");
exit(EXIT_FAILURE);
}
}
else if ( pid == -1 )
{
perror("fork\n");
exit(EXIT_FAILURE);
}
}
else if ( i != 2 )
{
pid = fork();
if ( pid == 0 )
{
if ( i != 0 )
{
if ( dup2(pfd[(i-1)*2],0) < 0 )
{
perror("dup2\n");
exit(EXIT_FAILURE);
}
}
if ( dup2(pfd[i*2+1],1) < 0 )
{
perror("dup2\n");
exit(EXIT_FAILURE);
}
for ( j = 0; j < 4; j++ )
{
close(pfd[j]);
}
if (i == 0)
{
if ( execvp(ls[0],ls) < 0 )
{
perror("execvpls\n");
exit(EXIT_FAILURE);
}
}
else if ( i == 1 )
{
if ( execvp(sort[0],sort) < 0 )
{
perror("execvpsort\n");
exit(EXIT_FAILURE);
}
}
}
else if ( pid == -1 )
{
perror("fork\n");
exit(EXIT_FAILURE);
}
}
}
for ( j = 0; j < 4; j++ )
{
close(pfd[j]);
}
while(waitpid(0,0,0)>=0);
return 0;
}
EDIT: The number that it should print should be 19 for my directory