gpt4 book ai didi

c++ - 检查文件描述符中可用缓冲区字符的数量

转载 作者:行者123 更新时间:2023-12-02 09:52:34 25 4
gpt4 key购买 nike

如何检查套接字文件描述符的缓冲区中有多少个可用字符?
我想推迟从套接字读取字节,直到至少有8个字节可用(以下消息的长度)。我正在使用select()等待传入数据。当调用套接字的读取处理程序时,如果少于8个字节可用,我希望它只返回而不读取。
套接字甚至可以可读但只能少于8个字节吗?
有没有一个Linux系统调用可以检索多少个可从套接字读取的字节,而无需实际读取它们?

最佳答案

您可以将 ioctl() FIONREAD(SIOCINQ)请求一起使用。
tcp(7)联机帮助页:

The following ioctl(2) calls return information in value. The correct syntax is:

int value;
error = ioctl(tcp_socket, ioctl_type, &value);

ioctl_type is one of the following:

SIOCINQ
Returns the amount of queued unread data in the receive buffer. The socket must not be in LISTEN state, otherwise an error (EINVAL) is returned. SIOCINQ is defined in <linux/sockios.h>. Alternatively, you can use the synonymous FIONREAD, defined in <sys/ioctl.h>.

...


udp(7)联机帮助页:

These ioctls can be accessed using ioctl(2). The correct syntax is:

int value;
error = ioctl(udp_socket, ioctl_type, &value);

FIONREAD (SIOCINQ)
Gets a pointer to an integer as argument. Returns the size of the next pending datagram in the integer in bytes, or 0 when no datagram is pending. Warning: Using FIONREAD, it is impossible to distinguish the case where no datagram is pending from the case where the next pending datagram contains zero bytes of data. It is safer to use select(2), poll(2), or epoll(7) to distinguish these cases.

...


只要套接字的接收缓冲区在TCP中包含至少1个字节,在UDP中包含1个数据报,则该套接字将处于可读状态。或者,对于TCP,如果连接已被对等方正常关闭(已接收到 FIN数据包),则在这种情况下,后续读取将报告0字节。

关于c++ - 检查文件描述符中可用缓冲区字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63277370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com