Skip to content

Instantly share code, notes, and snippets.

@LiosK
Created December 27, 2010 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LiosK/756160 to your computer and use it in GitHub Desktop.
Save LiosK/756160 to your computer and use it in GitHub Desktop.
runfor -- Runs a command for a given time, kills it after the time is out.
ghc -W -O -threaded --make runfor
#!/bin/sh
ghc -W -O -threaded --make runfor
-- Runs a command for a given time, kills it after the time is out.
-- Licensed under the MIT License: Copyright (c) 2010-2011 LiosK.
import Control.Concurrent
import Control.Monad
import System
import System.Process
main = do
argv <- getArgs
when ("--help" `elem` take 1 argv) $ showUsage >> exitWith ExitSuccess
when (length argv < 2) $ do
putStr "Error: Specify required arguments: PROG and DURATION.\n"
showUsage >> exitFailure
let (n:prog:args) = argv
sec <- readIO n `catch` (\_ -> do
putStr "Error: Specify a proper DURATION.\n"
showUsage >> exitFailure)
(_, _, _, ph) <- createProcess $ proc prog args -- run target process
tk <- forkIO $ timekeeper sec ph -- run timekeeper thread
ec <- waitForProcess ph -- wait until the process ends or is killed by tk
killThread tk -- killThread does nothing when the thread is already dead
exitWith ec
timekeeper sec ph = do
threadDelay (sec * 1000000)
terminateProcess ph
showUsage = do
prog <- getProgName
putStr $ "Usage: " ++ prog ++ " DURATION PROG [ARG]...\n"
putStr $ "Execute a PROGram for DURATION seconds.\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment