[Haskell-cafe] How to redirect a handle within a thread (GHC 6.4.1 runtime)?

Robert Dockins robdockins at fastmail.fm
Wed Jan 18 16:06:06 EST 2006

On Jan 18, 2006, at 2:59 PM, Benjamin Franksen wrote:

> On Wednesday 18 January 2006 19:01, Dimitry Golubovsky wrote:
>> Is it possible to redirect a Handle (say stdout) somewhere only
>> within a running thread (started with forkIO) not touching the same
>> handle for the main and other threads?
>> I have a lot of code written with putStr(Ln) which was used in a
>> program acting as a filter, i. e. stdout was redirected by the
>> invoking shell. Now I want to run this code within a thread in other
>> program, but output must go to a file (or a pipe, or anywhere else a
>> file descriptor may be opened for). So fdToHandle is not good because
>> I need to modify the `stdout' only for that thread, not to create a
>> new Handle. Rewriting the code is not a convenient way (but will be
>> done if nothing else helps) because then I will need to pass that
>> handle around.
> Isn't this _the_ real-world example perfectly matching Robert Dockins'
> 'threadlocal' proposal?

Yes, actually.  This is precisely the use case that got me thinking  
about threadlocal storage in the first place.  I'm working on Shellac  
(http://www.mail-archive.com/haskell@haskell.org/msg17871.html) and  
it turns out that redirecting the standard output handle for a  
specific thread would be really nice.  The obvious alternative is to  
pass in a function of type (String -> IO ()) and pass it around, and  
make sure to use it instead of putStr and friends.  The non-obvious  
alternative is some unsafePerformIO hackery, as just posted.  Either  
way, its ugly.


Rob Dockins

Speak softly and drive a Sherman tank.
Laugh hard; it's a long way to the bank.
           -- TMBG

More information about the Haskell-Cafe mailing list