How much data is in pipe(c++)

Ham*_*JML 0 c++ pipe

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);
Run Code Online (Sandbox Code Playgroud)

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

iab*_*der 6

来自管道的数据量可能是无限的,就像流一样,size管道中没有概念.如果您不希望它阻止,如果没有什么可读,您应该O_NONBLOCK在调用时设置标志pipe2():

pipe2(pipefd, O_NONBLOCK);
Run Code Online (Sandbox Code Playgroud)

这种方式当你调用read()没有数据时它会失败并设置errnoEWOULDBLOCK

if (read(fd, ...) < 0) {
   if (errno == EWOULDBLOCK) {
      //no data
   }
   //other errors
}
Run Code Online (Sandbox Code Playgroud)

从手册页:

O_NONBLOCK:在两个新的打开文件描述上设置O_NONBLOCK文件状态标志.使用此标志可以节省对fcntl(2)的额外调用,以实现相同的结果.

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