When you have finished using a socket, you can simply close its
file descriptor with close
; see Opening and Closing Files.
If there is still data waiting to be transmitted over the connection,
normally close
tries to complete this transmission. You
can control this behavior using the SO_LINGER
socket option to
specify a timeout period; see Socket Options.
You can also shut down only reception or transmission on a
connection by calling shutdown
, which is declared in
sys/socket.h.
int
shutdown (int socket, int how)
¶Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
The shutdown
function shuts down the connection of socket
socket. The argument how specifies what action to
perform:
SHUT_RD
¶Stop receiving data on the socket.
SHUT_WR
¶Indicate to the peer that no further data will be transmitted on the socket. This indication is ordered with regard to past send operations on the socket, and data pending at the time of the call is still delivered.
SHUT_RDWR
¶Combine the actions of SHUT_RD
and SHUT_WR
.
The return value is 0
on success and -1
on failure. The
following generic errno
error conditions are defined for this
function:
EBADF
socket is not a valid file descriptor.
ENOTSOCK
socket is not a socket.
ENOTCONN
socket is not connected.
Additional errors can be reported for specific socket types.
The exact impact of the shutdown
function depends on the socket
protocol and its implementation. In portable code, the shutdown
function cannot be used on its own to gracefully terminate a connection
which is operated in full-duplex mode (with both peers sending data).
On Linux, when SHUT_RD
is used to shut down a TCP socket, any
pending data in the incoming socket buffer and any data that arrives
subsequently is discarded, without reporting an error or generating a
TCP RST segment. Attempts to read data from this socket using
recv
and similar functions (see Receiving Data) return zero.
(Other systems may treat SHUT_RD
with pending data as a data loss
event and generate RST segments. Linux AF_LOCAL
/AF_UNIX
sockets also report errors to peers.)
Similarly, when SHUT_WR
is used on a Linux TCP socket, a FIN
segment is sent to the peer, ordered after any data written previously
to the socket. After encountering the FIN segment, the peer will
recognize this as an end-of-stream condition.