如何每次都跟踪最大数量的文件描述符而不是使用 FD_SETSIZE (可能非常大)?到目前为止的代码是(改编自Beginning Linux Programming, 2nd Edition):
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <unistd.h>
#define SERVER_PORT 9734
#define ALLOWED_CLIENTS INADDR_ANY
#define BACKLOG 5
#define DELAY 0
int main()
{
int server_sockfd, client_sockfd;
socklen_t server_len, client_len;
struct sockaddr_in server_address, client_address;
int result;
fd_set readfds, testfds;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(ALLOWED_CLIENTS);
server_address.sin_port = htons(SERVER_PORT);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, BACKLOG);
FD_ZERO(&readfds); /* Initialise readfds fd_set struct */
FD_SET(server_sockfd, &readfds); /* Initialise readfds to handle input from server_sockfd */
while(1) {
char ch;
int fd;
int nread;
testfds = readfds;
printf("Server waiting...\n");
/* Wait indefinitely for client request (input) using testfds */
result = select(FD_SETSIZE, &testfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0);
if(result < 1) {
perror("Server 5");
exit(1);
}
/* At this stage, activity of a client trying to connect has been found.
* We will find which descriptor it is on by checking each in turn. */
for(fd = 0; fd < FD_SETSIZE; fd++)
{
if(FD_ISSET(fd, &testfds)) { /* If activity occurs on the given file descriptor... */
if(fd == server_sockfd) { /* If activity occurs on server_sockfd, it must be
* a request for a new connection */
client_len = sizeof(client_address);
/* Extract connection request - set client_sockfd equal to this */
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
/* Add client_sockfd to the descriptor set */
FD_SET(client_sockfd, &readfds);
printf(" -Added client (fd %d)\n", fd);
}
else
{
ioctl(fd, FIONREAD, &nread); /* Find out how much data needs to be read in */
if(nread == 0) { /* No data left - finished with this client */
close(fd);
FD_CLR(fd, &readfds);
printf(" -Removed client (fd %d)\n", fd);
}
else {
read(fd, &ch, 1); /* Carry out the server's actual function */
sleep(DELAY);
printf(" -Serving client (fd %d)\n", fd);
ch++;
write(fd, &ch, 1);
}
}
}
}
}
}
这本书继续说这会降低效率,这是有道理的,并且应该使用一个变量来跟踪连接的最大 fd 数,但我只是不知道如何实现这一点,有花了很长时间做实验。提前致谢。