如何使用fgets / fread读取PIPE

时间:2017-11-29 23:19:42

标签: pipe fgets fread

我有两个进程A,B和一个管道(my_pipe [2]),我需要进程A来读取进程B的输出。在进程B中,我有dup2(my_pipe[1], stdout);在A中,我需要继续读取B的输出并逐行处理。

我想在A中使用fread/fgets而不是read,但my_pipe[0]是文件描述符而不是* FILE。如何将fread / fgets用于管道?

1 个答案:

答案 0 :(得分:3)

Use fdopen()(使用POSIX参考,因为您已经在使用POSIX文件描述符):

  

NAME

fdopen - associate a stream with a file descriptor
     

概要

[CX] [Option Start] #include <stdio.h>

FILE *fdopen(int fildes, const char *mode); [Option End]
     

说明

The fdopen() function shall associate a stream with a file descriptor.

The mode argument is a character string having one of the following values:

r or rb
    Open a file for reading.
w or wb
    Open a file for writing.
a or ab
    Open a file for writing at end-of-file.
r+ or rb+ or r+b
    Open a file for update (reading and writing).
w+ or wb+ or w+b
    Open a file for update (reading and writing).
a+ or ab+ or a+b
    Open a file for update (reading and writing) at end-of-file.
     

这些标志的含义与fopen()中的指定完全相同,只是以w开头的模式不会导致文件被截断。

例如:

FILE *fptr = fdopen( fd, "rb" );

然后,您可以在fread()上使用fgets()fptr(以及其他)。