[Haskell-cafe] network's example echo server seems leaking socket on error binding

Merijn Verstraaten merijn at inconsistent.nl
Sat May 9 09:45:47 UTC 2020

> On 9 May 2020, at 10:15, Compl Yue <compl.yue at gmail.com> wrote:
> Is my suspicion correct ? Or I missed something that the example actually won't leak on binding errors ?

You are correct, the allocation in "open" must be atomic (so either fully succeed or allocate nothing), else it will leak resources.

The open here needs further bracketing internally to properly/safely handle this case. One solution would be to use bracketOnError (which only runs the cleanup on exception in the body), creating the socket in the "alloc" of bracketOnError, then do the binding inside the body of bracketOnError and returning the bound socket. So

open addr = bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close $ \sock -> do
        setSocketOption sock ReuseAddr 1
        withFdSocket sock setCloseOnExecIfNeeded
        bind sock $ addrAddress addr
        listen sock 1024
        return sock

Alternatively this can be addressed by Acquire from the resourcet package.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: Message signed with OpenPGP
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20200509/b4710ee7/attachment.sig>

More information about the Haskell-Cafe mailing list