Problem
How can I discard queued data when closing a socket? Will
shutdown(SSC) flush this data from the socket?Even using shutdown(SSC) to shut down both the read-half and write-half of the socket connection will not totally discard all the queued data.
For example, shutdown(sockfd, 2) will result in:
* closure of the read-half of the socket * no more data can be received * any data in the receive buffer is discarded * closure of the write-half of the socket * no further data can be sent * any data currently in send buffer will attempt to be delivered
Solution
Instead, consider changing the operation of close(S) on the socket by enabling the linger socket option SO_LINGER (setsockopt(SSC)). For example, setting l_onoff=1 and l_linger=0 (see <sys/socket.h>) will result in the connection being aborted when closed, discarding any data that still remains in the socket send and receive buffers.
The following code fragment demonstrates how this can be achieved:
#include <sys/types.h>
#include <sys/socket.h>/* cc ... -lsocket */void main(int argc, char *argv[]) { int ret, sockfd; struct linger Linger_str;
/*....*/Linger_str.l_onoff = 1; /* enable linger */
Linger_str.l_linger = 0; /* no timeout */
if (setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &Linger_str,
sizeof(struct linger)) == 0)
{
/* linger option set successfully */
/*...*/
} /*...*/
}NOTE: The following paragraph in setsockopt(SSC) relating to SO_LINGER
should be disregarded, as it is incorrect:Due to artifacts of the current implementation, the linger option no longer has an effect. It is still recognized by the system for backward compatibility.