I keep getting a "Accept: too many files" error after running my server.c code. Trying to get it to create new threads for clients and limit connections with semaphores.
This is my code:
#define MAX_CLIENTS 30
sem_t s;
void *handle(void *pnewsock);
int sockfd, new_fd, numbytes; // listen on sock_fd, new connection on new_fd
struct sockaddr_in my_addr; // my address information
struct sockaddr_in their_addr; // connector's address information
socklen_t sin_size;
pthread_t thread;
int main(void){
//initialise locks
sem_init(&s, 0, 0);
/* generate the socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(true);
}
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_port = htons(MYPORT); // short, network byte order
my_addr.sin_addr.s_addr = INADDR_ANY; // auto-fill with my IP
/* bind the socket to the end point */
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \
== -1) {
perror("bind");
exit(true);
}
/* start listnening */
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(true);
}
printf("server starts listening ...\n");
/* Main loop */
while (1) {
sin_size = sizeof(struct sockaddr_in);
if (pthread_create(&thread, NULL, handle, &new_fd) != 0) {
fprintf(stderr, "Failed to create thread\n");
}
}
return 0;
}
void *handle(void *pnewsock){
int value;
sem_getvalue(&s,&value);
while (value >= MAX_CLIENTS){
printf("too many connections");
sem_wait(&s);
}
if (value < MAX_CLIENTS){
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
&sin_size)) == -1) {
perror("accept");
exit(1);
}
printf("server: got connection from %s\n", \
inet_ntoa(their_addr.sin_addr));
char buffer[MAXDATASIZE];
char res[MAXDATASIZE];
memset(buffer, '\0', MAXDATASIZE);
memset(res, '\0', sizeof(res));
if ((numbytes=recv(new_fd, buffer, sizeof(buffer), 0)) == -1) {
perror("recv");
exit(true);
}
else if(numbytes == 0) {
printf("client left");
sem_post(&s);
close(new_fd);
exit(false);
}
else {
buffer[numbytes] = '\0'; // add null terminator
printf("Request: %s\n",buffer);
//search function
}
}
close(new_fd);
exit(false);
return NULL;
}
Can anyone give me some insight to this file leak? Thanks