| 1 | {-# LANGUAGE ScopedTypeVariables #-} |
|---|
| 2 | module Main where |
|---|
| 3 | import System.Environment |
|---|
| 4 | import System.Process |
|---|
| 5 | import Control.Monad |
|---|
| 6 | import Control.Concurrent |
|---|
| 7 | import System.IO |
|---|
| 8 | import Control.Applicative |
|---|
| 9 | import Control.Exception (handle, throwIO, Exception(..), SomeException) |
|---|
| 10 | import Network(listenOn, PortID(..)) |
|---|
| 11 | import Network.Socket |
|---|
| 12 | import System.IO |
|---|
| 13 | import System.Directory |
|---|
| 14 | import System.FilePath |
|---|
| 15 | |
|---|
| 16 | sGetLine' :: Socket -> IO String |
|---|
| 17 | sGetLine' s = reverse <$> go [] |
|---|
| 18 | where go xs = do |
|---|
| 19 | (x,n) <- recvLen s 1 |
|---|
| 20 | if x == "\n" || n <= 0 |
|---|
| 21 | then return xs |
|---|
| 22 | else go $ x++xs |
|---|
| 23 | |
|---|
| 24 | listenSock sk = forkIO . forever $ handle (\ (e::SomeException) -> print e) $ do |
|---|
| 25 | (resp,_) <- accept sk |
|---|
| 26 | forkIO $ handle (\(e::SomeException) -> sClose resp) $ forever $ sGetLine' resp >>= \line -> case line of |
|---|
| 27 | ('q':_) -> throwIO $ userError "exit" |
|---|
| 28 | ('l':_) -> launchNew |
|---|
| 29 | x -> putStrLn x |
|---|
| 30 | return () |
|---|
| 31 | |
|---|
| 32 | launchNew = do |
|---|
| 33 | pn <- getProgName |
|---|
| 34 | dir <- getCurrentDirectory |
|---|
| 35 | forkIO $ runProcess (dir </> pn) ["arg"] Nothing Nothing Nothing Nothing Nothing >> forever (threadDelay 100000) |
|---|
| 36 | return () |
|---|
| 37 | |
|---|
| 38 | main = do |
|---|
| 39 | hSetBuffering stdout NoBuffering |
|---|
| 40 | putStrLn "hi" |
|---|
| 41 | args <- getArgs |
|---|
| 42 | case args of |
|---|
| 43 | [] -> do sk <- listenOn $ PortNumber 9020 |
|---|
| 44 | listenSock sk |
|---|
| 45 | return () |
|---|
| 46 | _ -> putStrLn "subprogram launched" |
|---|
| 47 | forever $ threadDelay 1000000 |
|---|