我在子进程中执行此操作:execlp ("wc", "wc",filename,"-l", NULL)
并重定向管道中的输出以从父进程读取.
一切正常,但是当 wc
选项找不到指定的文件名时,它会导致无限循环。与查找选项相同。
我如何检查 execlp
的输出或者我应该怎么做才能不进入这个无限循环?
这是使用 fork 创建的 child 的代码:
close(1);
if (dup (pipeCom[1]) != 1)
{
fprintf (stderr, "dup - 1\n");
exit (1);
}
execlp ("wc", "wc" ,filename,"-l", NULL);`
这是来自父进程的代码:
wait();
if ((num = read(pipeCom[0],&out,200))==0)
perror("pipe error");
else {
out[num] = '\0';
}
printf("%s",out);
最佳答案
Jonathan 关于 dup2() 和“-l”选项的位置是完全正确的。 也就是说,SSCCE会是这样的:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
const char *filename = "/etc/passwd"; /* whatever */
int pipeCom[2];
char out[200];
int num, status;
if(pipe(pipeCom)) {
perror("pipe");
return 111;
}
if(argv[1])
filename = argv[1];
switch(fork()) {
case -1:
perror("fork");
return 111;
case 0:
/* child */
close(1);
if (dup (pipeCom[1]) != 1)
{
fprintf (stderr, "dup - 1\n");
exit (1);
}
execlp ("wc", "wc" ,filename,"-l", NULL); /* Jonathan! */
perror("wc");
return 111;
default:
/* parent */
wait(&status);
if ((num = read(pipeCom[0],&out,200))==0)
perror("pipe error");
else {
out[num] = '\0';
}
printf("%s",out);
break;
}
return 0;
}
由于没有参数的 wait(),您的原始代码甚至无法编译;简单地修复它导致一个程序可以编译并在我的系统上运行,所以...... 您能否张贴准确给您带来麻烦的代码片段,准确您如何编译/运行它以及准确失败的原因?我的直觉告诉我 filename==NULL 在你的情况下,但如果是这样的话,在你的程序中阅读它比想象它要好很多;p
关于c - 在子进程中执行并发送到管道,结果导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19466944/