From d5884388b09347835df599d8a0dcea77e6795c10 Mon Sep 17 00:00:00 2001 From: Joey Hess Date: Mon, 11 Jun 2012 00:39:09 -0400 Subject: daemonize git annex watch --- Utility/Daemon.hs | 39 +++++++++++++++++++++++++++++++++++++++ Utility/LogFile.hs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 Utility/Daemon.hs create mode 100644 Utility/LogFile.hs (limited to 'Utility') diff --git a/Utility/Daemon.hs b/Utility/Daemon.hs new file mode 100644 index 000000000..be3df17b7 --- /dev/null +++ b/Utility/Daemon.hs @@ -0,0 +1,39 @@ +{- daemon functions + - + - Copyright 2012 Joey Hess + - + - Licensed under the GNU GPL version 3 or higher. + -} + +module Utility.Daemon where + +import System.Posix +import System.Directory +import System.Exit +import Control.Monad + +{- Run an action as a daemon, with all output sent to a file descriptor. + - + - Does not return. -} +daemonize :: Fd -> Bool -> IO () -> IO () +daemonize logfd changedirectory a = do + _ <- forkProcess child1 + end + where + child1 = do + _ <- createSession + _ <- forkProcess child2 + end + child2 = do + when changedirectory $ + setCurrentDirectory "/" + nullfd <- openFd "/dev/null" ReadOnly Nothing defaultFileFlags + _ <- redir nullfd stdInput + mapM_ (redir logfd) [stdOutput, stdError] + closeFd logfd + a + end + redir newh h = do + closeFd h + dupTo newh h + end = exitImmediately ExitSuccess diff --git a/Utility/LogFile.hs b/Utility/LogFile.hs new file mode 100644 index 000000000..7ffb63f52 --- /dev/null +++ b/Utility/LogFile.hs @@ -0,0 +1,31 @@ +{- log files + - + - Copyright 2012 Joey Hess + - + - Licensed under the GNU GPL version 3 or higher. + -} + +module Utility.LogFile where + +import Common + +import System.Posix + +openLog :: FilePath -> IO Fd +openLog logfile = do + rotateLog logfile 0 + openFd logfile WriteOnly (Just stdFileMode) + defaultFileFlags { append = True } + +rotateLog :: FilePath -> Int -> IO () +rotateLog logfile num + | num >= 10 = return () + | otherwise = whenM (doesFileExist currfile) $ do + rotateLog logfile (num + 1) + renameFile currfile nextfile + where + currfile = filename num + nextfile = filename (num + 1) + filename n + | n == 0 = logfile + | otherwise = logfile ++ "." ++ show n -- cgit v1.2.3