This looks like a bit messy code for me.
If the open socket process terminates and there is some unwritten data in the socket, the kernel will break the socket without flushing out the unsent data.
When you write something on a socket, written data will not necessarily be transmitted immediately. The kernel supports a small buffer that collects data written to the socket. Or a pipe. It is more efficient for the process to continue and then the kernel will take care of the actual transfer of the recorded data when it has time for this.
The process can obviously write data to the socket much faster than it can be transmitted over a typical network interface, and the size of the internal buffer of the socket is limited, so if the process continues to write data to the socket, at some point it will fill the internal buffer and will have to wait for the kernel to actually transmit data, and delete the recorded data from the internal buffer before there is more room for recording.
[*] I omit some technical details, for example, that data is not considered to be recorded until the receiver accepts it.
In any case, the purpose of this call to sleep () is to provide some time for the actual transfer of the internal buffer before the process terminates, because if it does this before the actual data is written, the kernel will win. Don’t bother sending it and terminate the socket as I just mentioned.
This is a bad example. This is the wrong way to do such things. The socket should just be close () d. This will properly clean things and make sure that everything happens where it should go. I see no good reason why this example simply incorrectly closed the socket instead of tackling this kind of hacker.
source share