Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why need to sleep(1) to allow socket to drain?

Tags:

c++

c

sockets

I downloaded the source code for a simple static web server from http://www.ibm.com/developerworks/systems/library/es-nweb/sidefile1.html

However, I'm confused by line 130:

#ifdef LINUX
sleep(1);       /* to allow socket to drain */    
#endif

exit(1);

Since there is no close for the socket, does it mean I need to wait the client close the socket?

like image 463
ggaaooppeenngg Avatar asked Oct 06 '14 01:10

ggaaooppeenngg


1 Answers

Regardless of the author's intent, it is needless and incorrect. exit() is sufficient. When close() is called on a TCP socket, or exit() is called to terminate the process, unless SO_LINGER socket option has been set to a non-default setting, the kernel will keep the socket(s) in a wait state and attempt to deliver any undelivered / buffered data. You can see this with netstat, and is the reason that fast restarting a TCP server that isn't written for fast restart will have a problem reopening the port quickly (there is a proper way to accomplish this too).

I disagree with a couple of things in the accepted answer.

close() and exit() should have the same effect on the socket, traditionally it has only been a matter of style whether to close sockets if you were about to exit.

It should have nothing to do with overflowing a TCP send buffer, since it happens after all the writes. Full write buffer will return an error immediately by the write() return code; sleeping at the end will be irrelevant to that.

sleep(1) should have no effect on the socket buffer or reliable data delivery. If anything, this code throttles the web server child processes after the writes, so really has no good effect, and could actually increase the potential of a denial of service attack.

I am describing default operation. The defaults can be changed via the many options.

For the "bible" on socket programming, see W. Richard Steven's UNIX Network Programming - Networking APIs: Sockets and XTI where he covers this in detail.

like image 136
codenheim Avatar answered Sep 18 '22 10:09

codenheim