【发布时间】:2019-12-30 15:13:51
【问题描述】:
我正在使用 C 进行管道实现。我必须编写 (grep -rF regex directory | tee output.txt | wc -l) 的 C 等效项。但是,代码无法继续超出 tee 等效项。 (以下代码中标记的循环永远不会终止)。我不明白为什么循环没有终止,为什么管道的输出没有传递给newpipe 的输入。
当我删除 while 循环时,程序终止,输出为 0。
int newpipe[2],p[2],pid;
char * argv_list1[] = {"grep","-rF","regex","directory",NULL};
char * argv_list2[] = {"wc","-l",NULL};
char *file="output.txt";
pid=fork();
if(pid==0){
int pid2=fork();
if(pid2==0){
close(p[0]);
dup2(p[1],1);
execvp("grep",argv_list1);
}
else{
wait(NULL);
int fd=open(file, O_RDWR | O_CREAT |O_TRUNC,0666);
close(newpipe[0]);
close(p[1]);
dup2(p[0], 0);
printf("pid2=%d\n",pid2);
dup2(newpipe[1],1);
char tmp;
while(read(p[0],&tmp,1)){
write(fd,&tmp,1);
write(1,&tmp,1);
}//This loop never terminates and the output comes on standard output
exit(1);
}
}
else{
wait(NULL);
close(newpipe[1]);
dup2(newpipe[0],0);
execvp("wc",argv_list2);
}
【问题讨论】:
标签: c pipe fork system-calls child-process