Why FD_SET/FD_ZERO for select() inside of loop?(为什么 FD_SET/FD_ZERO for select() 在循环内?)
问题描述
我正在使用 select 函数在我的套接字之间进行通信.我有一个 while 循环,我这样做 -
I am using the select function for communication between my sockets. I have a while loop and I do -
while(!done) {
FD_ZERO(&read_flags);
FD_ZERO(&write_flags);
FD_SET(comm_fd1, &read_flags);
FD_SET(comm_fd2, &read_flags);
FD_SET(STDIN_FILENO, &read_flags);
FD_SET(comm_fd1, &write_flags);
FD_SET(comm_fd2, &write_flags);
FD_SET(STDIN_FILENO, &write_flags);
//call select
sel = select(comm_fd1+comm_fd2+1, &read_flags, &write_flags, (fd_set*)0, &waitd);
和客户端的不同变量相同.我从在线教程中获得了这项基本技术,然后就开始使用了.然后它击中了我 - 为什么我每次循环时都清除设置并添加文件描述符?如果它们已经添加,为什么要清除它们并再次添加?所以我之前只尝试过一次,代码不再相同了.有人可以解释为什么吗?仅仅是因为select修改了set的内容吗?感谢任何帮助和/或见解.
and the same with different variables on the client side. I got this basic technique from a tutorial online and just went with it. Then it hit me - why do I clear the set and add file descriptors each time I loop? If they are already added, why clear them and add again? So I tried only doing this once before the while, and the code does not work the same anymore. Can someone explain why? Is it just because select modifies the contents of the set? Any help and/or insight is appreciated.
推荐答案
当 select
返回时,它更新了集合以显示哪些文件描述符已准备好读取/写入/异常.所有其他标志都已清除.
When select
returns, it has updated the sets to show which file descriptors have become ready for read/write/exception. All other flags have been cleared.
在开始另一个选择之前重新启用已清除的文件描述符很重要,否则,您将不再等待这些文件描述符.
It's important that you re-enable the file descriptors that were cleared prior to starting another select, otherwise, you will no longer be waiting on those file descriptors.
关于重新清除,可以养成一个好习惯,因为如果你需要改变文件描述符的集合(比如添加一个新打开的套接字到读集),你需要清除并每次都重新构建它,以便随着程序状态的变化而正确.
As for re-clearing, it can be a good habit to get into, since if you need to change the set of file descriptors (such as adding a newly opened socket to the read set), you'll want to clear it and rebuilt it every time, so that it's correct as the state of the program changes.
这篇关于为什么 FD_SET/FD_ZERO for select() 在循环内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 FD_SET/FD_ZERO for select() 在循环内?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07