
On 9 May 2020, at 10:15, Compl Yue
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. Cheers, Merijn