Portable keyboard signal handling

Robert Dockins robdockins at fastmail.fm
Thu Aug 31 15:49:45 EDT 2006


Friends,

I have a Haskell library that is currently GHC-only.  However, I'm  
working on making it more portable, with the short-term goal of  
running on Hugs and the hope of being Haskell' compliant when the  
time comes.  One problem I've run into is that I need a way to  
portably handle Ctrl-C.  On Posix systems, this can be done in a  
pretty straightforward manner using System.Posix.Signals.  However,  
for win32, I've been relying on the GHC.ConsoleHandler module, which  
is obviously GHC-specific.  Because the module is short, I've  
attached the complete code text to the end of this message.

So, my question is, what should my strategy be?  I could snarf the  
entire contents of GHC.ConsoleHandler into my project (yuck!).  I  
could try to get the ConsoleHandler module out of the GHC walled  
garden.  I could try to get the 'withControlCHandler' function into a  
future release of the standard libs .  Or...

What do you think?  Have I missed some other option?


Rob Dockins

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






module System.Console.Shell.ConsoleHandler
( withControlCHandler
) where

import qualified Control.Exception as Ex

#ifndef mingw32_HOST_OS

import qualified System.Posix.Signals as PS

withControlCHandler :: IO () -> IO a -> IO a
withControlCHandler hdl m =
   Ex.bracket
       (PS.installHandler PS.keyboardSignal (PS.Catch hdl) Nothing)
       (\oldh -> PS.installHandler PS.keyboardSignal oldh Nothing)
       (\_ -> m)

#else

import qualified GHC.ConsoleHandler as CH


handleCtrlC :: IO () -> CH.Handler
handleCtrlC hdl = CH.Catch $ \ev ->
    case ev of
      CH.ControlC -> hdl
      _           -> return ()


withControlCHandler :: IO () -> IO a -> IO a
withControlCHandler hdl m =
   Ex.bracket
       (CH.installHandler (handleCtrlC hdl))
       (\oldh -> CH.installHandler oldh)
       (\_ -> m)


#endif



More information about the Libraries mailing list