Are handles closed automatically when they fall out of scope?

Simon Marlow simonmar at microsoft.com
Mon Oct 25 08:02:05 EDT 2004


On 22 October 2004 21:58, Peter Simons wrote:

> I know it's a rather mundane question, but I couldn't find
> an answer to it!
> 
> So what does happen when I forget to hClose a Handle? Will
> the garbage collector do that for me? Or not?

Yes, a Handle will be automatically closed sometime after it becomes
unreferenced.  However, the party line is "don't rely on this
behaviour", because it is inherently unpredictable, and if you get it
wrong you can end up running out of file descriptors.  hClose explicitly
when you can.

> And more specifically, what about the handles
> runInteractiveProcess returns? Do I have to close the
> "stdin" Handle? All of them? What happens when I use
> terminateProcess? Do I have to hClose them nonetheless?

The stdin handle is attached to a pipe, and you get the behaviour you
expect when you close the write end of a pipe: if a process tries to
read the other end of the pipe, it will get EOF.  After
terminateProcess, if you write to the stdin handle, you're likely to get
SIGPIPE on Unix.

(BTW, I assume you have a good reason for wanting to call
terminateProcess).

> And while I am at it: How about Socket? Do I have to sClose
> a socket I obtained from listenOn or accept?

A Socket isn't finalized automatically (that is, you need explicit
sClose). However, if you use socketToHandle, then the Handle will be
finalized, and hence the socket closed, when it becomes unreachable.

On 24 October 2004 23:37, John Goerzen wrote:

> * What happens when one Handle corresponding to a socket is closed,
>   but another isn't?

You shouldn't have two Handles on the same socket.  This is an unchecked
error.

> * What happens when one gets GC'd but another doesn't?

See above.

Cheers,
	Simon


More information about the Glasgow-haskell-users mailing list