运行 与标准输入、标准输出并发处理

Run processes concurrently with stdin, stdout

如何扩展“Running processes concurrently”以包含标准输入和标准输出?

例如,假设我的 (Windows) 命令在 stdout 上输出 10,我想检查所有进程的输出是否正确:

let cmds = replicate 100 "echo 10"

我应该如何编写 Haskell 程序?

import Control.Concurrent.Async
import System.IO
import System.Process

您链接的网站上的代码使用 runCommand; the equivalent that gives you access to the streams is runInteractiveCommand. You can then use hGetContents 从流中读取。

-- | Run @echo 10@ and tests whether the output is what we expect.
testOne :: IO Bool
testOne =
  runInteractiveCommand "echo 10" >>= \(_stdin, stdout, _stderr, _proc) ->
  hGetContents stdout >>= \out ->
  return (out == "10\n")

然后我们可以使用 async 包中的 replicateConcurrently 到 运行 它并发 100 次,然后 fmap (all id) 对结果取布尔值 的所有结果。

-- | Run 'testOne' 100 times concurrently, return whether all tests succeeded.
testMany :: IO Bool
testMany =
  all id <$> replicateConcurrently 100 testOne