gpt4 book ai didi

c - select 中使用的 fd_set 如何检查位掩码?

转载 作者:行者123 更新时间:2023-12-04 10:16:12 25 4
gpt4 key购买 nike

根据这篇文章poll vs select vs event-based :

select() only uses (at maximum) three bits of data per file descriptor, while poll() typically uses 64 bits per file descriptor. In each syscall invoke poll() thus needs to copy a lot more over to kernel space. A small win for select().

这里是 fd_set 的实现(在 Advisories : multiple applications fd_set structure bitmap array index overflow 上找到

#ifndef FD_SETSIZE
#define FD_SETSIZE 1024
#endif
#define NBBY 8 /* number of bits in a byte */
typedef long fd_mask;
#define NFDBITS (sizeof (fd_mask) * NBBY) /* bits per mask */
#define howmany(x,y) (((x)+((y)-1))/(y))
typedef struct _types_fd_set {
fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
} _types_fd_set;

#define fd_set _types_fd_set

所以,最终,fd_set 只是一个long 的数组。还写着:

A call to FD_SET sets a bit to 1 using socket number as an index:

这意味着,如果我有一个 socket fd number 5,索引为 5 的元素将被选中,它的第一位将从 0 翻转到 1。由于 select() 使用 3 位,我猜其他两位是用于发送和接收的。它是否正确?为什么 select() 在只需要 3 位时使用 long?

此外,如上所述,poll() 使用 64 位进行检查。为什么 poll 需要检查 pollfd 结构中的每一位?这是 pollfd 结构:

struct pollfd {
int fd; // the socket descriptor
short events; // bitmap of events we're interested in
short revents; // when poll() returns, bitmap of events that occurred
};

结构中的总位数是 64 位,一个 32 位 int 和两个 16 位 short。我知道检查位标志的常用方法是使用 AND (&) 运算符来过滤掉其他不相关的位。这适用于这种情况吗?

最佳答案

poll() typically uses 64 bits per file descriptor. In each syscall invoke poll() thus needs to copy a lot more over to kernel space. A small win for select().

谬论——如果你只想监视一个 fd,poll(2) 会让你摆脱那 64 位,而对于 select(),你必须复制多达 12288 位(3 组,每组 4096 位)通常)。

此外,poll() 支持值大于 FD_SETSIZE 的 fd

关于c - select 中使用的 fd_set 如何检查位掩码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8532852/

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