0

我在子进程中执行此操作:execlp ("wc", "wc" ,filename,"-l", NULL)并将管道中的输出重定向到从父进程中读取。

All working good but when wcoption doesn't find the specified file name it cause an infinite loop. 与查找选项相同。

我如何检查输出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);
4

1 回答 1

1

乔纳森关于 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

于 2013-10-20T14:05:11.333 回答