如何忽略 CHILD 进程中的空管道?

How to ignore empty pipes in CHILD process?

我在我的 child 进程中使用名为 read_from_pipe 的子例程,如下所示,以读取管道中的任何内容并显示它:

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 是另一个检查文件描述符是否存在的子程序。

问题是因为我在我的 parent 中使用了 waitpid(pid, &status, 0); 语句来等待 child 完成它的任务,编译器陷入了第一次冷 运行 at while 当管道实际为空时循环。我如何 AND 我的 while 中的另一个条件让编译器简单地忽略空管道?

其实很简单,你只需要忽略SIGPIPE信号,调用一个函数就搞定了:

signal(SIGPIPE, SIG_IGN);

当管道为空时,不会发出 SIGPIPE 信号,从管道读取将 return 文件结束值(底层 read 系统调用将 return 0).