Linux FD_ISSET
时间: 2023-11-30 14:38:19 浏览: 40
Linux FD_ISSET 是一个宏定义,用于检查文件描述符集合中是否存在指定的文件描述符。它通常与 select 函数一起使用,用于多路复用 I/O 操作。
具体来说,FD_ISSET(fd, &fdset) 会检查 fdset 集合中是否包含 fd 文件描述符,如果包含则返回非零值,否则返回 0。
例如,下面的代码片段演示了如何使用 select 和 FD_ISSET 实现简单的网络服务器:
```
fd_set read_fds;
int max_fd = listen_fd;
FD_ZERO(&read_fds);
FD_SET(listen_fd, &read_fds);
while (true) {
fd_set tmp_fds = read_fds;
int nready = select(max_fd + 1, &tmp_fds, NULL, NULL, NULL);
if (nready == -1) {
perror("select");
exit(EXIT_FAILURE);
}
for (int fd = 0; fd <= max_fd; ++fd) {
if (FD_ISSET(fd, &tmp_fds)) {
if (fd == listen_fd) {
// 处理新连接
int conn_fd = accept(listen_fd, NULL, NULL);
if (conn_fd == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
FD_SET(conn_fd, &read_fds);
max_fd = std::max(max_fd, conn_fd);
} else {
// 处理已连接套接字上的数据
char buf[1024];
ssize_t nread = read(fd, buf, sizeof(buf));
if (nread == -1) {
perror("read");
exit(EXIT_FAILURE);
} else if (nread == 0) {
// 客户端关闭连接
close(fd);
FD_CLR(fd, &read_fds);
} else {
// 处理客户端发送的数据
handle_data(fd, buf, nread);
}
}
}
}
}
```