Are handles closed automatically when they fall out of scope?

John Goerzen jgoerzen at complete.org
Mon Oct 25 15:33:29 EDT 2004


On 2004-10-25, Simon Marlow <simonmar at microsoft.com> wrote:
>> 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.
>
> Hmmm, you should still be able to *write* to a socket handle that has
> had hGetContents applied to it.  In GHC, a ReadWrite handle to a socket
> basically consists of a wrapper around two independent Handles, one for
> read and one for write, each with its own buffer.

You were right.  Long story, but I had a different bug that happened to
get fixed at the same time.

Which brings up another question:

The problem was that I was trying to *read* using hGetContents more than
once.  I have this data structure:

data FTPConnection = FTPConnection {readh :: IO String,
                                    writeh :: Handle,
                                    socket_internal :: Socket,
                                    isPassive :: Bool}

Now, if I set readh to to be hGetContents h, then the first read I try to
make using it works, but subsequent ones don't, since the first one made
it half-closed already.

If I make readh a plain string, instead of an IO String, then each time
I try to read from it, I start back at the very beginning -- reading the
same response from the network over and over, in other words.

In this case, my workaround was to write my own simple version of
hGetContents that uses hGetChar and doesn't make anything half-closed.

Maybe there's a better way?

> If you do socketToHandle twice, then the danger is that one of the
> Handles will be finalized and close the FD before the other Handle has
> finished with it.

In this particular case, my data structure is opaque, so nobody else
will be able to access the underlying handles.  But thanks for the
caution -- I will be sure to remember that.

-- John



More information about the Glasgow-haskell-users mailing list