0
我正在写一个C程序,它运行多个管道的以下Linux命令:如何在Linux中使用C中的多个管道运行命令?
cat myfile1.txt | egrep Computing |厕所-l> MYFILE
我的代码如下:
int p_fd[2];
pid_t childpid, waitReturn;
int pid=1;
int status, i;
pipe(p_fd);
for(i = 1 ; i < 3 ; i++)
if(childpid = fork())
break;
else
pid++;
while(childpid != (waitReturn = wait(&status)))
if((waitReturn == -1) && (errno != EINTR))
break;
if (childpid > 0 && pid == 1){
printf("%d\n", pid);
int fd;
if ((fd= open("myfile", O_CREAT|O_RDWR|O_TRUNC, 00644)) == -1)
{
printf("Error: Cannot open file in open()\n");
exit(1);
}
close(0);
dup(p_fd[0]);
close(1);
dup(fd);
close(p_fd[0]);
close(p_fd[1]);
close(fd);
execl("/bin/wc", "wc", "-l", NULL);
}else if(childpid > 0 && pid == 2){
printf("%d\n", pid);
close(0);
dup(p_fd[0]);
close(1);
dup(p_fd[1]);
close(p_fd[0]);
close(p_fd[1]);
execl("/bin/egrep", "egrep", "Computing", NULL);
}else if(childpid == 0 && pid == 3){
printf("%d\n", pid);
close(1);
dup(p_fd[1]);
close(p_fd[0]);
close(p_fd[1]);
execl("/bin/cat", "cat", "myfile1.txt", NULL);
}
return 0;
然而,我的程序,当它到达挂起 “EXECL(”/斌/ egrep的”, “egrep的”, “计算”, NULL);“,在第二个孩子中用pid 2调用。
我不知道为什么我的程序挂在那里;是关于管道的僵局吗?
任何人都可以帮助我修改上述程序,以便它可以给我想要的结果吗?
无用的'猫'奖励给你。你的表达应该是'egrep计算myfile1.txt | wc -l> myfile'开头。 –