[Libevent-users] SO_LINGER option for sockets created by evhttp

Scott Lamb slamb at slamb.org
Fri Dec 14 15:56:00 EST 2007


Ilya Martynov wrote:
> Hi,
> 
> I wonder if anybody could elaborate what is the reason for setting
> SO_LINGER option for sockets created by evhttp. I mean this part of code
> inside of http.c:
> 
> static int
> bind_socket_ai(struct addrinfo *ai)
> {
>         ...
>         linger.l_onoff = 1;
>         linger.l_linger = 5;
>         setsockopt(fd, SOL_SOCKET, SO_LINGER, (void *)&linger,
> sizeof(linger));
>         ...
> }
> 
> If I'm reading the documentation correctly at least for Linux this
> makes close() on the socket to block what probably not a very good thing
> in programs based on libevent. From
> http://linux.about.com/od/commands/l/blcmdl7_socket.htm:
> 
> SO_LINGER
>     Sets or gets the SO_LINGER option. ... When enabled, a close(2) or
> shutdown(2) will not return until all queued messages for the socket
> have been successfully sent or the linger timeout has been reached.
> Otherwise, the call returns immediately and the closing is done in the
> background.
> 

I ran a bunch of tests on linger a while ago (by creating a socket pair 
and programmatically manipulating firewall rules to simulate packet 
loss). My results agree with your conclusion - this can cause the 
process to block for l_linger seconds on Linux. On OS X, this does *not* 
block if the socket is non-blocking - the behavior is not consistent 
between platforms.

My conclusions were basically that the only use of SO_LINGER is to force 
an RST by passing {1, 0}. The default is {0, 0}.

Tests and results here:

http://www.slamb.org/svn/repos/trunk/projects/socket_tests/index.html

I didn't test if linger options are inherited from the listen socket to 
accepted sockets, which this code seems to be assuming.


More information about the Libevent-users mailing list