BruceTerp
BruceTerp

Reputation: 45

how to use fgets/fread to read a PIPE

I have two processes A, B and a pipe(my_pipe[2]) between them, I need process A to read the output of process B. In process B, I have dup2(my_pipe[1], stdout); in A, I need to keep reading the output of B and process it line by line.

I want to use fread/fgets in A instead of read, but my_pipe[0] is a file descriptor instead of a *FILE. How can I use fread/fgets for a pipe?

Upvotes: 0

Views: 1631

Answers (1)

Andrew Henle
Andrew Henle

Reputation: 1

Use fdopen() (using the POSIX reference since you're already using POSIX file descriptors):

NAME

fdopen - associate a stream with a file descriptor

SYNOPSIS

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

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

DESCRIPTION

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.

The meaning of these flags is exactly as specified in fopen(), except that modes beginning with w shall not cause truncation of the file.

For example:

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

Then you can use fread() and fgets() (among others) on fptr.

Upvotes: 3

Related Questions