withFile defeats dead handle closure

Viktor Dukhovni ietf-dane at dukhovni.org
Wed Dec 30 21:32:40 UTC 2020

On Wed, Dec 30, 2020 at 02:23:20PM -0500, David Feuer wrote:

> withFile keeps the handle it creates alive until the user action completes.
> If we want to avoid this, we can. All that's required is to capture the
> weak reference that holds the handle's finalizer. Then instead of closing
> the handle in the end (or on exception) using hClose, withFile can run the
> handle's finalizer. Should we do this? Or does it run too much against the
> idea that handles should be managed as explicitly as possible?

I'm not sure what you mean by "keeps alive", it passes the handle to the
action, and closes it when the action returns, but the action, can (if
it so chooses) also close the handle in a more timely manner, because
"hClose" is idempotent.  So it does not seem like any change is needed
here...  Am I missing something?

The below compiles and runs, with no errors:

    module Main (main) where
    import System.IO

    main :: IO ()
    main = do
        withFile "/etc/passwd" ReadMode $ \f -> hClose f >> hClose f
        withFile "/etc/passwd" ReadMode $ \f -> hClose f >> hClose f


More information about the Libraries mailing list