Title is self-explanatory on what I want to do so here is my current code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
pid_t pid ;
int fd[2], fd2[2];
pipe(fd);
pipe(fd2);
pid = fork();
if(pid == 0) {
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
char *exp[] = {"cat", "filename.txt", NULL};
execvp("cat", exp);
exit(EXIT_FAILURE);
}
else if(pid > 0) {
close(1);
dup(fd2[1]);
close(fd2[0]);
close(fd2[1]);
char *exp[] = {"grep", "-w", "stringname", NULL};
execvp(exp[0], exp);
pid_t pid2=fork();
close(0);
dup(fd[0]);
close (fd[1]);
close(fd[0]);
char *exp2[] = {"grep", "-c", "stringname", NULL};
execvp(exp2[0], exp2);
exit(EXIT_FAILURE);
}
else {
printf("Error in forking");
exit(EXIT_FAILURE);
}
close(fd[0]);
close(fd[1]);
close(fd2[0]);
close(fd2[1]);
return 0;
}
Currently the program is compiling but not executing (it gets stuck somewhere on execution and I don't get any output), any help on what I am doing wrong and how can I fix it?
if(pid2>0)
after creating the second process, will do that nowgrep
that is writing intofd2
is blocked on a read.close(fd2[0])
in the start of parent process?