简体   繁体   中英

How much data is in pipe(c++)

I am trying to guess how much data is in pipe, and I don't want to use while(read) because it is blocking until EOF.

Is there any way to do that?

I real I want something like this:

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

I say again, I don't want to use while (read) because it is blocking until EOF.

The amount of data coming from a pipe could be infinite, just a like a stream, there's no concept of size in a pipe. if you don't want it to block if there's nothing to read you should set the O_NONBLOCK flag when calling pipe2() :

pipe2(pipefd, O_NONBLOCK);

This way when you call read() if there's no data it would fail and set errno to EWOULDBLOCK

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

From the man page:

O_NONBLOCK: Set the O_NONBLOCK file status flag on the two new open file descriptions. Using this flag saves extra calls to fcntl(2) to achieve the same result.

You could also use select() on a blocking pipe to timeout.

This could help you, however it is unix specific:

#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";
}

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