Getting the file descriptor of a handle, without closing it

Volker Wysk pf3 at
Sun Mar 11 02:31:17 CET 2012


This is an addition to my previous post.

This modified version of main seems to work:

main = do

   fd <- unsafeWithHandleFd stdin return
   putStrLn ("stdin: fd = " ++ show fd)
   fd <- unsafeWithHandleFd stdout return
   putStrLn ("stdout: fd = " ++ show fd)

The way I understand it, unsafeWithHandleFd's job is to keep a reference to 
the hande, so it won't be garbage collected, while the action is still 
running. Garbage collecting the handle would close it, as well as the 
underlying file descriptor, while the latter is still in use by the action. 
This can't happen as long as use of the file descriptor is encapsulated in the 

This encapsulation can be circumvented by returning the file descriptor, and 
that's what the modified main function above does. This should usually never be 

However, I want to use it with stdin, stdout and stderr, only. These three 
should never be garbage collected, should they? I think it would be safe to 
use unsafeWithHandleFd this way. Am I right?

unsafeWithHandleFd is still broken (see previous message), but for my purposes 
it wouldn't necessarily need to be fixed.

Happy hacking
Volker Wysk

More information about the Glasgow-haskell-users mailing list