跳转至
第二部分 · 并发

33.3 使用select()

原书第 293–294 页
整章阅读 ↗

为了让这更具体,我们来看看如何使用select()来查看哪些网络描述符在它们上面有传入消息。图33.1 展示了一个简单的例子。

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    // open and set up a bunch of sockets (not shown)
    // main loop
     while (1) {
        // initialize the fd_set to all zero
        fd_set readFDs;
        FD_ZERO(&readFDs);

        // now set the bits for the descriptors
        // this server is interested in
        // (for simplicity, all of them from min to max)
        int fd;
        for (fd = minFD; fd < maxFD; fd++)
            FD_SET(fd, &readFDs);

        // do the select
        int rc = select(maxFD+1, &readFDs, NULL, NULL, NULL);

        // check which actually have data using FD_ISSET()
        int fd;
        for (fd = minFD; fd < maxFD; fd++)
            if (FD_ISSET(fd, &readFDs))
                processFD(fd);
    }
}

图33.1 使用select()的简单代码

这段代码实际上很容易理解。初始化完成后,服务器进入无限循环。在循环内部,它使用FD_ZERO()宏首先清除文件描述符集合,然后使用FD_SET()将所有从minFD 到maxFD的文件描述符包含到集合中。例如,这组描述符可能表示服务器正在关注的所有网络套接字。最后,服务器调用select()来查看哪些连接有可用的数据。然后,通过在循环中使用FD_ISSET(),事件服务器可以查看哪些描述符已准备好数据并处理传入的数据。

当然,真正的服务器会比这更复杂,并且在发送消息、发出磁盘I/O 和许多其他细节时需要使用逻辑。想了解更多信息,请参阅Stevens 和Rago 的书 [SR05],了解API 信息,或Pai 等人的论文、Welsh 等人的论文[PDZ99,WCB01],以便对基于事件的服务器的一般流程有一个很好的总体了解。