[Haskell-cafe] Are handles garbage-collected?

Sven Panne Sven.Panne at aedion.de
Sun Oct 24 05:17:20 EDT 2004


Tomasz Zielonka wrote:
> AFAIK, Handles have finalisers which close them, but I don't know if GHC
> triggers garbage collection when file descriptors run out.  If not, you
> will have problems if you manage to run out of fds between GCs.

Yes, in GHC and Hugs handles are flushed and closed automatically during GC
if they are garbage and not already closed. But no GC is triggered when one
runs out of native file descriptors. I'm not exactly sure about NHC, but I
guess it's the same there.

> How about using bracket to introduce explicit close on end of scope?

I would recommend this, too, e.g. via something like:

    withFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a
    withFile fileName mode = bracket (openFile fileName mode) hClose

This ensures that the handle is closed immediately even in the presence of
exceptions.

Cheers,
    S.


More information about the Haskell-Cafe mailing list