13 November 2010

Haskell daemon, cuid a dó

D'athfhachtóirigh (refactored) mé an cód:

Daemon.hs

module Daemon where

import System.Exit
import System.IO.Unsafe
import System.Posix.Signals
import Control.Concurrent

class DaemonState a where
  initialise :: IO a
  work :: a -> IO a
  finalise :: a -> IO ()

termReceived = unsafePerformIO (newMVar False)

handleTERM :: IO ()
handleTERM = swapMVar termReceived True >> return ()

loop :: (DaemonState a) => a -> IO (Maybe a)
loop d = do
  timeToStop <- readMVar termReceived
  if timeToStop
    then finalise d >> return Nothing
    else work d >>= loop

start :: (DaemonState a) => IO (Maybe a)
start = installHandler sigTERM (Catch handleTERM) Nothing >>  initialise >>= loop



Seo úsáid samplach:
Main.hs
module Main where

import Daemon

instance DaemonState Int where

initialise = do
  putStrLn "Starting up"
  return 0

work i = do
  putStrLn (show i)
  return (i+1)

finalise i = do
  putStrLn "Shutting down"
  return ()

main = start :: IO (Maybe Int)

No comments: