I have written a very small function in C, opens a socket, accepts connection and immediately closes them.
The problem is, each connections eats some memory without releasing it at anytime to the OS. I ran ab (apache benchmark) with about 300K requests, and the processes memory is continuously growing (at the end few hundred megabytes).
I'm aware that a process is not always returning its free memory to the OS. But as soon as it gets over few megabytes, I think it should return the memory or am I wrong?
This happens only on Windows. On Linux is my memory usage all the time nearly the processes startup usage.
Compiled with GCC 4.8.2. Tested on Windows Server 2008 R2 and Windows 8.1.
void http_server_start(void) {
int rc;
struct sockaddr_in cfg;
#ifdef _WIN32
WORD ver;
WSADATA data;
ver=MAKEWORD(2,2);
rc=WSAStartup(ver, &data);
if(rc != 0){
printf("Error: Unable to initialize WSA (%d)", rc);
}
#endif
memset(&cfg, 0, sizeof(cfg));
cfg.sin_family = AF_INET;
cfg.sin_addr.s_addr = htonl(INADDR_ANY);
cfg.sin_port = htons(PORT);
server = socket(AF_INET, SOCK_STREAM, 6);
int reuseaddr=1;
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseaddr, sizeof(reuseaddr)) == -1){
rc=GetLastErrorEx();
printf("Error: Unable to set SO_REUSEADDR (%d)\n", rc);
} else if (bind(server, (struct sockaddr *)&cfg, sizeof(cfg)) < 0 ) {
rc=GetLastErrorEx();
printf("Error: Unable to bind socket (%d)\n", rc);
close(server);
} else if (listen(server, QUEUE_SIZE) < 0) {
rc=GetLastErrorEx();
printf("Error: Unable to listen (%d)\n", rc);
close(server);
} else {
printf("Listening on %s:%d\n", inet_ntoa(cfg.sin_addr), ntohs(cfg.sin_port));
int client;
struct sockaddr_in addr;
int addrlen=sizeof(addr);
do {
client=accept(server, (struct sockaddr*)&addr, &addrlen);
if(client != -1){
shutdown(client, SHUT_RDWR);
close(client);
}
} while(1);
}
}
For closing the sockets you are using shutdown() and close(). Actually shutdown() forces the connection to be terminated even if there are several descriptors referring to the same socket, shutdown() allows for closing in only one direction and close() does not affect the state of the connection until the last descriptor is closed.
Try using
int closesocket(Socket S);
An application should always have a matching call to closesocket() for each successful call to socket to return any socket resources to the system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With