- while (!cleanup() && select(fd + 1, &rfds, NULL, NULL, NULL) != -1) {
- logthing(LOGTHING_INFO, "Accepted connection.");
- sock_accept(fd);
+ while (!cleanup() && select(maxfd + 1, &rfds, NULL, NULL, NULL) != -1) {
+ /*
+ * Deal with existing clients first; if we're at our
+ * connection limit then processing them might free
+ * things up and let us accept the next client below.
+ */
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (clients[i] != -1 &&
+ FD_ISSET(clients[i], &rfds)) {
+ logthing(LOGTHING_DEBUG,
+ "Handling connection for client %d.", i);
+ if (sock_do(dbctx, clients[i])) {
+ sock_close(clients[i]);
+ clients[i] = -1;
+ logthing(LOGTHING_DEBUG,
+ "Closed connection for client %d.", i);
+ }
+ }
+ }
+ /*
+ * Check if we have a new incoming connection to accept.
+ */
+ if (FD_ISSET(fd, &rfds)) {
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (clients[i] == -1) {
+ break;
+ }
+ }
+ if (i < MAX_CLIENTS) {
+ logthing(LOGTHING_INFO,
+ "Accepted connection %d.", i);
+ clients[i] = sock_accept(fd);
+ }
+ }
+ FD_ZERO(&rfds);