简体   繁体   English

为什么 FD_SET/FD_ZERO for select() 在循环内?

[英]Why FD_SET/FD_ZERO for select() inside of loop?

I am using the select function for communication between my sockets.我正在使用 select 函数在我的套接字之间进行通信。 I have a while loop and I do -我有一个while循环,我做 -

    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);

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?仅仅是因为select修改了set的内容吗? Any help and/or insight is appreciated.任何帮助和/或见解表示赞赏。

When select returns, it has updated the sets to show which file descriptors have become ready for read/write/exception.select返回时,它更新了集合以显示哪些文件描述符已准备好读取/写入/异常。 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.至于重新清除,可以养成一个好习惯,因为如果你需要改变文件描述符集(比如在读集中添加一个新打开的套接字),你会想要清除它并重新构建每次都这样做,以便随着程序状态的变化而正确。

Is it just because select modifies the contents of the set?仅仅是因为select修改了set的内容吗?

Yes, after select returns, only ready descriptors are left within the sets.是的,在select返回后,集合中只剩下准备好的描述符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM