Skip to content
Advertisement

Socket Server Memory usage goes up, becomes unresponsive

I have the following socket server code for Linux using Pthreads.

If I start stress testing this with:

JavaScript

The memory increases to about 270MB then the server becomes unresponsive:

JavaScript

On ARMv7 architecture this takes a shorter time. If I stop the requests with the for loop, the memory does not get freed up, meaning that this server would sooner or later crash anyway in production.

Compiles with:

JavaScript

What can be the problem in the following code?

JavaScript

Advertisement

Answer

The memory increases to about 270MB then the server becomes unresponsive

You want to either detach the threads created or join them.

As it stands each thread which ended is zombiing around with all its resource (stack and book keeping data) still being allocated. This eats up the server’s memory.

To have a thread detach, have it call

JavaScript

before it ends.

To join a thread have any other thread call pthread_join() passing the thread-id as returned by pthread_create().

As the program does not seem to be interested in the threads’ results, detaching them might be the preferred solution.


There are other issues with the code, which are unrelated to the resource leak:

  • how the code handles the result of recv().
  • error checking for most relevant function calls is missing.
  • new_sock = malloc(1); allocates to few memory for an int as new_sock is.
  • c should be of type socklen_t. Using the casting hammer on its address does not make things better
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement