Socket Resource Leak?

2007-12-24 21:05:00

Upon working on some code, I noticed that the process size and resident
resource size of my listener daemon seemed to grow about 4k every minute or
so leaving me with a 10MB process after about a day when I started with 2M.
I stripped my code down to just your basic multithreaded socket listener and
found that there was still something making my process grow large. If I
compile this on Linux, I don't see the same growth - it grows as it needs to
make room for the threads and whatnot but when the connections all
disconnect it goes back down to its normal size (not so with Solaris).

The problem ONLY exists if I use recv() or read() to read data from the
socket. If I comment out the recv() line, the process does not grow. Some
have suggested it could be buffering, but 1) it should free that buffer
space when the thread exits, and 2) read() doesn't buffer to my knowledge.

Is it possible I've stumbled across a resource leak in Solaris? Code below.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <errno.h>

int connection_handler(int sockfd);

int main(int argc, char **argv) {
int sockfd, newsockfd;
struct sockaddr_in addr, their_addr;
int sin_size = sizeof(struct sockaddr_in);
pthread_t thread;
int yes=1;

sockfd = socket(AF_INET, SOCK_STREAM, 0);

if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
perror("setsockopt");
exit(0);
}

memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(9000);
addr.sin_addr.s_addr = INADDR_ANY;

if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(0);
}

if (listen(sockfd, 32) == -1) {
perror("listen()");
exit(0);
}

while(1) {
if ((newsockfd = accept(sockfd, (struct sockaddr *)&their_addr,
&sin_size)) == -1) {
perror("accept()");
} else {

if (pthread_create(&thread, NULL, (void *) connection_handler, (void*)
newsockfd)) {
perror("pthread_create()");
}
}
}
}

int connection_handler(int sockfd) {
char buffer[2048];

pthread_detach(pthread_self());
recv(sockfd, buffer, sizeof(buffer), 0);
close(sockfd);
pthread_exit(0);

}

Comments

Got something to say?

You must be logged in to post a comment.