gpt4 book ai didi

c - select() 和 poll() 是无状态的是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 11:03:38 25 4
gpt4 key购买 nike

我想了解 epoll() 与 select() 和 poll() 有何不同。 select() 和 poll() 非常相似。 select() 允许您监视多个文件描述符,并检查这些文件描述符中的任何一个是否可用于操作(例如读、写)而不会阻塞。当超时到期时,select() 返回就绪的文件描述符,程序可以在不阻塞的情况下对这些文件描述符执行操作。

...
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don’t rely on the value of tv now! */

if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
...

poll() 更灵活一些,因为它不依赖位图,而是文件描述符数组。此外,由于 poll() 对请求的 (events) 和结果 (revents) 使用单独的字段,因此您不必担心重新填充被内核覆盖的集合。

...
struct pollfd fds[2];
fds[0].fd = open("/dev/dev0", ...);
fds[1].fd = open("/dev/dev1", ...);
fds[0].events = POLLOUT | POLLWRBAND;
fds[1].events = POLLOUT | POLLWRBAND;
ret = poll(fds, 2, timeout_msecs);
if (ret > 0) {
for (i=0; i<2; i++) {
if (fds[i].revents & POLLWRBAND) {
...

但是,我读到 poll() 也存在问题,因为 select() 和 poll() 都是无状态的;内核不在内部维护请求集。我读了这个:

Suppose that there are 10,000 concurrent connections. Typically, only a small number of file descriptors among them, say 10, are ready to read. The rest 9,990 file descriptors are copied and scanned for no reason, for every select()/poll() call. As mentioned earlier, this problem comes from the fact that those select()/poll() interfaces are stateless.

我不明白文件描述符是“复制”和“扫描”是什么意思。复制到哪里?我不知道“无国籍”是什么意思。感谢您的澄清。

最佳答案

“无状态”意味着“不保留两次调用之间的任何内容”。因此,在上述示例中,内核需要重建很多东西,但基本上什么也没有。

关于c - select() 和 poll() 是无状态的是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262230/

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