Technical article 109820

How can I discard queued data when closing a socket?

OpenServer 5.0.4OpenServer 5.0.5OpenServer 5.0.6

Written · Last revised

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.

From the Xinuos technical article database, record 109820. Reproduced with permission. The original is at www.sco.com/ta/109820, which is reachable but blocked from search engines. Xinuos marks this article against a retired product line. That refers to the product’s lifecycle, not to whether the advice still works — plenty of it still applies to running systems.

Next step

Need this fixed rather than explained?

Tell us the release, what the system runs and what it is doing. We will reply by email with what we would do next.

  • You deal with the people who do the work
  • No obligation, and no upgrade required before we will help
  • We tell you plainly if something is not worth doing

Send an enquiry

We reply by email. If a server is down, say so in the first line. You can also write to help@scoexpert.com.