简体   繁体   中英

Reading from pipe into buffer character by character/find the size of data in pipe

I'm currently working with pipes using "unistd.h" and "sys/wait.h" for my OS homework. I'm trying to implement graph pipe.

Since in graph pipe there is a possibility that output of a process can be sent to more than one process as an input, I need to store it in a buffer and send from it in a loop.

To read output from process, I use read() function. The problem is that since the number of characters in an output is variable, either I need to read it one character by one or somehow find the size of output.

I'm trying to do the first option. Here is my code

string buffer;
char temp[1];
while (/*condition*/)
{
    read (pipe[0], temp, 1);
    buffer.push_back (temp[0]);
}

My question is what is the condition that must be inside of loop?

PS If second option is easier then how can I check the size of output of a process in a pipe?

The condition is really the return of the read call:

while (read(...) == 1) { ... }

Also don't forget the address-of operator, you can use that instead of declaring temp as an array:

char temp;
while (read(pipe[0], &temp, sizeof(temp)) == sizeof(temp)) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM