0

我正在使用一个read_from_pipe在我的child过程中命名的子例程,如下所示来读取管道中的任何内容并显示它:

void read_from_pipe(int fileDescriptr)
{
    FILE *stream;
    int c;
    if (fileDesc_Is_Valid(fileDescriptr) == TRUE)
    {
        stream = fdopen(fileDescriptr, "r");
        while ((c = fgetc(stream)) != EOF)
            putchar(c);                                     
        fclose(stream);
    }
    else                                                     
        perror("Reading from pipe failed -->");
}

fileDesc_Is_Valid是另一个检查文件描述符是否存在的子程序。

问题是,因为我waitpid(pid, &status, 0);在我的语句中使用parent了等待完成其任务的语句,所以当管道实际上为空时child,编译器会卡在循环的第一次冷运行中。我while怎样才能让编译器简单地忽略空管道?ANDwhile

4

1 回答 1

0

它实际上非常简单,您只需要忽略SIGPIPE信号,只需一个函数调用即可完成:

signal(SIGPIPE, SIG_IGN);

SIGPIPE当管道为空时,从管道读取将返回文件结束值(底层read系统调用将返回0),而不是引发信号。

于 2015-10-14T11:04:50.080 回答