简体   繁体   English

从管道读取字符到缓冲区中的字符/查找管道中数据的大小

[英]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. 我目前正在使用将"unistd.h""sys/wait.h"用于操作系统的管道。 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. 要从进程读取输出,我使用read()函数。 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? PS如果第二个选项更简单,那么如何检查管道中进程的输出大小?

The condition is really the return of the read call: 条件实际上是read调用的返回:

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

Also don't forget the address-of operator, you can use that instead of declaring temp as an array: 同样不要忘记address-of运算符,您可以使用它代替将temp声明为数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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