RE: Are handles closed automatically when they fall out of scope?

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

Simon Marlow writes:
BTW, I assume you have a good reason for wanting to call terminateProcess
Yes, I have to abort the process in case of an exception in my code. Just giving it EOF is not enough, unfortunately. Thanks a lot for taking the time to answer, Simon. I really appreciate it. Peter P. S.: It might be worth adding a few sentences to the description of 'Handle' which explain these problems. I'm certain other users of the language will run into the same questions.

On 2004-10-25, Simon Marlow
On 22 October 2004 21:58, Peter Simons wrote:
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.
This does seem useful, though. I am actually doing this in my code and it works. One Handle is opened ReadOnly, the other WriteOnly. That way, I can use hGetContents on the reading side in my network code. If I tried that with a single Handle opened ReadWrite, then I'd get errors about it being closed whenever I'd try to write out some data. I wasn't able to find any other good way around it. -- John
participants (3)
-
John Goerzen
-
Peter Simons
-
Simon Marlow