我正在学习pipes,并遇到了问题。我希望我的程序能够按照以下方式工作:
grep [要查找的单词] [要搜索的文件] | grep -i [不包含此单词] | wc -l
它可以编译并且没有出现错误,但是没有输出(至少不是在stdout上),这很奇怪。当我尝试在最后一个fork中printf一些东西时,它会将其打印在stdin上。我没有在此fork或父进程中更改stdout,所以这对我来说似乎很奇怪。我正在尝试关闭未使用的pipes并刷新stdout(它还在执行吗?),但可能仍然有其他问题需要解决。#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void help() {
printf( "Usage of the 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 a 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 a 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;
}