[英]Execlp in child and send to pipe, result cause infinite loop
I am doing this in a child process: execlp ("wc", "wc" ,filename,"-l", NULL)
and redirecting the output in a pipe to read from father process. 我在子进程中执行此操作:
execlp ("wc", "wc" ,filename,"-l", NULL)
,并将输出重定向到从父进程读取的管道中。
All working good but when wc
option doesn't find the specified file name it cause an infinite loop. 一切正常,但是当
wc
选项找不到指定的文件名时,将导致无限循环。 Same thing with find option. 使用find选项也是一样。
How can i check the output of execlp
or what should i do to not get into this infinite loop? 我如何检查
execlp
的输出,或者应该怎么做才能避免进入此无限循环?
this is the code from child created with fork: 这是使用fork创建的子代的代码:
close(1);
if (dup (pipeCom[1]) != 1)
{
fprintf (stderr, "dup - 1\n");
exit (1);
}
execlp ("wc", "wc" ,filename,"-l", NULL);`
this is the code from parent process: 这是来自父进程的代码:
wait();
if ((num = read(pipeCom[0],&out,200))==0)
perror("pipe error");
else {
out[num] = '\0';
}
printf("%s",out);
Jonathan is absolutely right about dup2() and the position of the "-l" option. 对于dup2()和“ -l”选项的位置,乔纳森绝对正确。 That being said, an SSCCE would be like this:
话虽如此, 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;
}
Your original code wouldn't even compile because of wait() without parameters; 您的原始代码甚至由于没有参数的wait()而无法编译; simply fixing that led to a program that compiles and works on my system, so... Can you post exactly the piece of code that is giving you trouble, explaining exactly how you compile/run it and exactly what is failing?
只需解决导致开发可在我的系统上编译并运行的程序的问题,那么...您能准确地发布给您带来麻烦的那段代码, 确切地解释您如何编译/运行它,以及到底有什么失败吗? My guts tell me that filename==NULL in your case, but if that is the case, it would have been a lot better to read it in your program than to imagine it ;p
我的胆量告诉我,文件名==你的情况NULL,但如果是这样的话,那将是好了很多 ,在你的程序远比想象它来阅读它,P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.