如何在linux中获取管道中的可用数据

问题描述 投票:0回答:1

在 Linux 中,在管道中写入一些数据(尚未读取)后,在管道的读/写端使用

fstat
时,
st_size
字段为零。是否可以获得管道中可用数据的大小?

示例代码:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>

#define BUFLEN  8

int main() {
        char            buf[BUFLEN];
        int             fd[2];
        struct stat     sb;

        pipe(fd);

        write(fd[1], buf, BUFLEN);

        fstat(fd[1], &sb);                        // the same for fd[0]

        printf("pipe size=%ld\n", sb.st_size);    // print 0


        exit(0);
}
c linux pipe filesize
1个回答
0
投票

手册页 pipeline(7) 的内容如下:

   The following ioctl(2) operation, which can be applied to a file
   descriptor that refers to either end of a pipe, places a count of
   the number of unread bytes in the pipe in the int buffer pointed
   to by the final argument of the call:

       ioctl(fd, FIONREAD, &nbytes);

   The FIONREAD operation is not specified in any standard, but is
   provided on many implementations.

所以有些系统有非标准的

ioctl
操作来获取管道中未读的字节数。

© www.soinside.com 2019 - 2024. All rights reserved.