Haskell 从进程中读取

Haskell read from process

我不太确定问题出在哪里,所以我不确定标题是否真的准确。我想打开一个 shell 进程,写入它然后读取输出:

import System.IO (hPutStr, hGetContents, hSetBuffering, hClose,
            BufferMode(NoBuffering))
import System.Process (runInteractiveProcess)

main = do
        (hIn, hOut, _, _) <- runInteractiveProcess
                                "/bin/sh" [] Nothing Nothing
        hSetBuffering hIn NoBuffering
        hPutStr hIn "ls /\n"
        hGetContents hOut >>= putStrLn
        hClose hIn
        hClose hOut

这似乎有效(有点):

$ ./mwe
bin
boot
cdrom
dev
etc
...

问题是,程序挂起(我需要用 Ctrl-C 终止它)。我想 shell 仍然是 运行,这会阻止 Haskell prohram 退出。所以我试图用 terminateProcess:

显式终止 shell
main = do
        (hIn, hOut, _, sh) <- runInteractiveProcess
                                "/bin/sh" [] Nothing Nothing
        hSetBuffering hIn NoBuffering
        hPutStr hIn "ls /\n"
        hGetContents hOut >>= putStrLn
        terminateProcess sh
        hClose hIn
        hClose hOut

但无济于事。我还尝试将 exit 发送到 shell:

    ...
    hGetContents hOut >>= putStrLn
    hPutStr hIn "exit\n"
    ...

这也不行。

我确定解决方案非常简单,但我找不到它(尝试搜索 "haskell kill process",等等,但也许问题不是我想的那样)。如果已经有人问过这个问题,请提前致歉。非常感谢任何帮助!

我有一些 haskell 代码可以从 shell 进程中读取内容,但它不会挂起....试一试:

import System.Process
import GHC.IO.Handle.Text

main :: IO ()
main = do
   (_,Just ho1, _, hp1) <- createProcess (shell "find -iname \"*.lhs\""){std_out=CreatePipe}
   sOut <- hGetContents ho1
   _ <- waitForProcess hp1

那么,sOut就会有shell过程的内容