简体   繁体   English

如何通过Linux中的索引访问fd_set中的FD?

[英]How to access FDs in fd_set through indexing in Linux?

For example, I can access them with fd_set.fd_array[i] in Windows.. 例如,我可以在Windows中使用fd_set.fd_array[i]访问它们。

request_list getIncomingRequests()
{
    fd_set master_set_copy = master_set;
    request_list requests;
    int socket_count = select(0, &master_set_copy, nullptr, nullptr, nullptr);
    for (int i = 0; i < socket_count; ++i)
    {
    #ifdef _WIN32
        auto req_fd = master_set_copy.fd_array[i];
    #else
        auto req_fd = master_set_copy...[i]; // ??
    #endif
        sockaddr_in req_addr;
        getsockname(req_fd, (sockaddr*)&req_addr, &addr_len);
        requests.push_back(request(req_fd, this->fd, req_addr));
    }
    return requests;
}

But fd_array doesn't exist in Linux so I need an equivalent. 但是fd_array在Linux中不存在,因此我需要一个等效的。

The POSIX implementation of fd_set does not require that the structure has the field fd_array . fd_set的POSIX实现不需要结构具有字段fd_array fd_set is supposed to be an opaque data structure. fd_set应该是不透明的数据结构。

You can check which file descriptors are set by iterating through all supported descriptors ( 0 through FD_SETSIZE-1 ) and calling FD_ISSET() . 您可以通过迭代所有受支持的描述符( 0FD_SETSIZE-1 )并调用FD_ISSET()来检查设置了哪些文件描述符。

Note from the manual page: 手册页中的注释

select() can monitor only file descriptors numbers that are less than FD_SETSIZE ; select()只能监视小于FD_SETSIZE文件描述符号; poll(2) does not have this limitation. poll(2)没有此限制。 See BUGS. 参见错误。

Add a new variable, maybe max_fd , that tracks the highest numbered file descriptor in the set. 添加一个新变量,也许是max_fd ,该变量跟踪集合中编号最高的文件描述符。 Then you can do this: 然后,您可以执行以下操作:

request_list getIncomingRequests()
{
    fd_set master_set_copy = master_set;
    request_list requests;
    int socket_count = select(max_fd + 1, &master_set_copy, nullptr, nullptr, nullptr);
    for (int req_fd = 0; req_fd <= max_fd; ++req_fd)
    {
        if (!FD_ISSET(req_fd, &master_set_copy))
            continue;
        sockaddr_in req_addr;
        getsockname(req_fd, (sockaddr*)&req_addr, &addr_len);
        requests.push_back(request(req_fd, this->fd, req_addr));
    }
    return requests;
}

But you're probably better off using poll instead of select . 但是您最好使用poll而不是select

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

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