----------------------------------------------------------------------------
-- |
-- Module      :  Utils
-- Copyright   :  (c) Jan Vornberger 2009
-- License     :  BSD3-style (see LICENSE)
--
-- Maintainer  :  jan.vornberger@informatik.uni-oldenburg.de
-- Stability   :  unstable
-- Portability :  not portable
--
-----------------------------------------------------------------------------

module Utils where

import System.Posix
import System.IO

-- | Launch an external application through the system shell and return a @Handle@ to its standard input.
spawnPipe :: String -> IO Handle
spawnPipe x = do
    (rd, wr) <- createPipe
    setFdOption wr CloseOnExec True
    h <- fdToHandle wr
    hSetBuffering h LineBuffering
    forkProcess $ do
        createSession
        uninstallSignalHandlers
        dupTo rd stdInput
        executeFile "/bin/sh" False ["-c", x] Nothing
    return h

uninstallSignalHandlers :: IO ()
uninstallSignalHandlers = do
    installHandler sigCHLD Default Nothing
    return ()
