Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 31st, 2012  |  syntax: None  |  size: 1.53 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to handle signal on windows with haskell?
  2. import IO
  3. import Control.Exception hiding (catch)
  4. import Control.Concurrent
  5. import Network
  6. import System.Posix   ---cannot be run on windows.
  7.  
  8. main = withSocketsDo (installHandler sigPIPE Ignore Nothing >> main')
  9.     --so the signal handler cannot be used
  10.  
  11. main' = listenOn (PortNumber 9900) >>= acceptConnections
  12.  
  13. acceptConnections sock = do
  14.         putStrLn "trying to accept" -- debug msg
  15.         conn@(h,host,port) <- accept sock
  16.         print conn -- debug msg
  17.         forkIO $ catch (talk conn `finally` hClose h) (e -> print e)
  18.         acceptConnections sock
  19.  
  20. talk conn@(h,_,_) = hGetLine h >>= hPutStrLn h >> hFlush h >> talk conn
  21.        
  22. void callback(int sig)
  23. {
  24.    // printf("catchn");
  25. }
  26. ...
  27. signal(SIGINT,callback);
  28.        
  29. -- unix-src/OSCompat.hs
  30. module OSCompat where
  31. import System.Posix
  32. ignorePipe = installHandler sigPIPE Ignore Nothing
  33.  
  34. -- Win32-src/OSCompat.hs
  35. module OSCompat where
  36. import System.Win32
  37. ignorePipe = -- ???
  38.        
  39. if os(windows)
  40.     build-depends: Win32
  41.     hs-source-dirs: Win32-src
  42. else
  43.     build-depends: unix
  44.     hs-source-dirs: unix-src
  45.        
  46. import OSCompat
  47. main = withSocketsDo (ignorePipe >> main')
  48.        
  49. import Foreign
  50. import Foreign.C.Types
  51.  
  52. type Handler = CInt->IO ()
  53. foreign import ccall "wrapper"
  54.   genHandler:: (Handler) -> IO (FunPtr Handler)
  55.  
  56. foreign import ccall safe "signal.h signal"
  57.         install:: CInt->FunPtr Handler->IO CInt
  58. main=do
  59.         s<-genHandler (x->putStrLn $ "catch "++(show x))
  60.         res<- install 2 s
  61.         putStrLn $ show res
  62.         s<-getLine