Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux socket released too slowly when program killed

Tags:

c

linux

sockets

EDIT: tl;dr:

Don't open sockets with the wrong options, it's unlikely to work!

Original Question:

I'm working with a program which doesn't have a clean shutdown mechanism, it just relies on being killed to terminate it.

It opens a socket as follows:

(void) setsockopt(h, SOL_SOCKET, (SO_KEEPALIVE | SO_REUSEADDR), (int *) & optval, sizeof( optval ));

The re-use address option does seem to work, in that eventually the socket is released after the program dies. Eventually being anything from a couple of seconds up to maybe a minute.

This is quite tedious as I need to restart this program regularly. Making the program teminate properly would be a very big job, but I'm wondering if there's anything more local I can do to release the socket earlier?

like image 658
Stefan Avatar asked Jun 28 '26 20:06

Stefan


1 Answers

Socket options are not bits and hence can not be or'ed like SO_KEEPALIVE | SO_REUSEADDR. To be pedantic, SO_KEEPALIVE | SO_REUSEADDR yields another socket option SO_NO_CHECK.

You don't notice this mistake because you don't check the return value of setsockopt. Now you know why ignoring return values is considered bad practice.

like image 68
Maxim Egorushkin Avatar answered Jul 01 '26 15:07

Maxim Egorushkin