i'm learning pipes , have occured problem. want program work as:
grep [word find] [file search] | grep -i [without word] | wc -l
compiles , works no errors, gives no output(at least not on stdout want do). strange, when try printf sth in last fork it's printing on stdin. im not changing stdout in fork or in parrent process seems weird me. i'm trying close unused pipes , flush stdout(is still doing sth here?), there still sth more do.
#include<stdio.h> #include<stdlib.h> #include<unistd.h> void help() { printf( "usage of program:\n" "\t./alagrep [filetosearch] [wordtofind] [wordtoexpel]\n"); } int main(int argc, char *argv[]) { if(argc != 4) { help(); exit(exit_failure); } int fd[2]; if(pipe(fd) != 0) { printf("error while opening pipe.\n"); exit(exit_failure); } pid_t pid; if((pid = fork()) == -1) { printf("error while forking.\n"); exit(exit_failure); } else if(pid == 0) { close(fd[0]); if(dup2(fd[1],stdout_fileno) < 0) { printf("cannot duplicate stdout.\n"); _exit(exit_failure); } close(fd[1]); execl("/bin/grep","grep",argv[2],argv[1],null); fflush(stdout); } close(fd[1]); int fd1[2]; if(pipe(fd1) != 0) { printf("error while opening pipe.\n"); exit(exit_failure); } if((pid = fork()) == -1) { printf("error while forking.\n"); exit(exit_failure); } else if(pid == 0) { close(fd1[0]); if(dup2(fd[0],stdin_fileno) < 0) { printf("cannot duplicate stdin.\n"); _exit(exit_failure); } if(dup2(fd1[1],stdout_fileno) < 0) { printf("cannot duplicate stdout.\n"); _exit(exit_failure); } close(fd[0]); close(fd1[1]); execl("/bin/grep","grep","-i",argv[3],null); fflush(stdout); } close(fd[0]); close(fd1[1]); if((pid = fork()) == -1) { printf("error while forking.\n"); exit(exit_failure); } else if(pid == 0) { close(fd1[1]); if(dup2(fd1[0],stdin_fileno) < 0) { printf("cannot duplicate stdin.\n"); _exit(exit_failure); } close(fd1[0]); execl("/bin/wc","wc","-l",null); fflush(stdout); } close(fd1[0]); return 0; }
i'm not sure why bu using execlp
instead of execl
helped. execl
process couldnt find text file. althoug gave him path it. guess execl
working in other directory.
Comments
Post a Comment