Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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