In the Network.Socket package, there is an echo server example. In the echo server, a call to withFdSocket sock setCloseOnExecIfNeeded
is made just before actually binding to the socket. The relevant function is below:
open :: AddrInfo -> IO Socket
open addr = E.bracketOnError (openSocket addr) close $ \sock -> do
setSocketOption sock ReuseAddr 1
withFdSocket sock setCloseOnExecIfNeeded
bind sock $ addrAddress addr
listen sock 1024
return sock
The full example can be found on the Network.Socket package documentation.
What is the purpose of this call? It's my understanding that withFdSocket
creates a file descriptor associated with the socket, and setCloseOnExecIfNeeded
sets the CLOEXEC flag on the descriptor. However this descriptor is immediately 'discarded' and nothing is done with it.
Am I confused that the file descriptor always exists and withFdSocket
just provides this existing descriptor, which we have to update with the flag in order for the socket to close when the program exits?
CodePudding user response:
withFdSocket
does not create an Fd
; it just reads the one already stored inside the socket data structure.