pipe(c++)中有多少数据

How much data is in pipe(c++)

本文关键字:多少 数据 c++ pipe      更新时间:2023-10-16

我试图猜测管道中有多少数据,但我不想使用while(read)因为它在EOF之前阻塞。

有什么办法可以做到这一点吗?

我真的我想要这样的东西:

i = pipe1.size();
pipe1.read(i);

再说一遍,我不想使用while (read)因为它在 EOF 之前会阻塞。

来自管道的数据量可能是无限的,就像一个流一样,管道中没有size的概念。 如果您不希望它在没有任何可读取的内容时阻塞,则应在调用pipe2()时设置O_NONBLOCK标志:

pipe2(pipefd, O_NONBLOCK);

这样,当您调用read()如果没有数据时,它将失败并将errno设置为 EWOULDBLOCK

if (read(fd, ...) < 0) {
   if (errno == EWOULDBLOCK) {
      //no data
   }
   //other errors
}

从手册页:

O_NONBLOCK:在两个新打开的文件上设置O_NONBLOCK文件状态标志 文件说明。 使用此标志可以节省对 fcntl(2) 的额外调用 达到相同的结果。

您也可以在阻塞管道上使用 select() 来超时。

这可以帮助你,但它是特定于 unix 的:

#include <iostream>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <errno.h>
int pipe_fd; /* your pipe's file descriptor */
......
int nbytes = 0;
//see how much data is waiting in buffer
if ( ioctl(pipe_fd, FIONREAD, &nbytes) < 0 )
{
    std::cout << "error occured: " << errno;
}
else 
{
    std::cout << nbytes << " bytes waiting in buffer";
}