Hi i was writing a program to do cat inputs.txt | sort | uniq in c programming using pipe, fork and dup2 but the program seems to not run any thing at all. I placed a printf at the beginning, right after main() and i do not see any output still.I have no idea what is going on in the background or why is this happening?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(){
printf("we are here");
int pipe1[2];
int pipe2[2];
if(pipe(pipe1)==-1){
perror("failed to pipe\n");
exit(1);
}
int process1=fork();
if(process1<0){
perror("failed to create the first child1\n");
exit(1);
}else if(process1>0){
if(close(pipe1[0])==-1){
perror("failed to close the first pipe read\n");
exit(1);
}
if(dup2(pipe1[1],1)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(close(pipe1[1])==-1){
perror("failed to close the first pipe write\n");
exit(1);
}
execlp("cat","cat","inputs.txt",NULL);
perror("failed to exec\n");
exit(1);
}else if(process1==0){
if(pipe(pipe2)==-1){
perror("failed to pipe\n");
exit(1);
}
int process2=fork();
if(process2<0){
perror("failed to create the first child1\n");
exit(1);
}else if(process2==0){
if(close(pipe2[1])==-1){
perror("failed to close the second pipe write-third process\n");
exit(1);
}
if(dup2(pipe2[0],0)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(close(pipe2[0])==-1){
perror("failed to close the second pipe read-third process\n");
exit(1);
}
execlp("uniq","uniq",NULL);
perror("failed to exec\n");
exit(1);
}else if(process2>0){
if(close(pipe1[1])==-1){
perror("failed to close the first pipe write\n");
exit(1);
}
if(close(pipe2[0])==-1){
perror("failed to close the second pipe read\n");
exit(1);
}
if(dup2(pipe1[0],0)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(dup2(pipe2[1],1)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(close(pipe1[0])==-1){
perror("failed to close the first pipe read\n");
exit(1);
}
if(close(pipe2[1])==-1){
perror("failed to close the second pipe write\n");
exit(1);
}
execlp("sort","sort",NULL);
perror("failed to exec\n");
exit(1);
}
}
}