subprocess - LWT 与子流程的简单交互

标签 subprocess ocaml ocaml-lwt

这是一个使用 Unix 模块与子进程交互的简单程序。我只是启动一个 cat shell 命令,向它发送一个字符串并读回它:

#load "unix.cma";; (* Needed if you are in the toplevel *)

let () =
    let sin, sout, serr = Unix.open_process_full "cat" [||]  in
    output_string sout "test\n";
    flush sout;
    input_line sin |> print_string;
    flush stdout;
    Unix.close_process_full (sin, sout, serr) |> ignore;;

最近我开始研究 Lwt 库,我想用它重现相同的功能。我认为以下应该有完全相同的结果:

    #use "topfind";;                (*                            *)
    #thread;;                       (* Also only for the toplevel *)
    #require "lwt.simple-top";;     (*                            *)

    let () =
        let open Lwt in
        let process = Lwt_process.open_process_full ( "cat" , [||]  ) in
        Lwt_io.write_line process#stdin "test\n"
        >>= ( fun ()  -> Lwt_io.flush process#stdin  )
        >>= ( fun ()  -> Lwt_io.read  process#stdout )
        >>= ( fun str -> Lwt_io.print str            )
        >>= ( fun ()  -> Lwt_io.flush Lwt_io.stdout  )
        |> Lwt_main.run

但它并没有像我预期的那样工作——显然它读取并打印了一个空字符串。

我想我对 Lwt 应该如何工作有一些基本的困惑,但我想不通。谁能告诉我如何使用 Lwt 与子进程通信?

最佳答案

使用 Lwt_process.shell 进行正确的命令,在您的情况下,正确的命令如下:

Lwt_process.shell "cat";;
- : Lwt_process.command = ("", [|"/bin/sh"; "-c"; "cat"|])

此外,我怀疑,在您以正确的方式运行您的程序之后,您会想知道,为什么您的程序会阻塞。这是因为 cat 进程在您将 EOF 写入其输入 channel 之前不会完成。这就是 Lwt_io.read 调用永远不会完成的原因。一种解决方案是关闭 stdin channel 。

关于subprocess - LWT 与子流程的简单交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36140076/

相关文章:

functional-programming - 用函数式语言生成所有排列

python - OSError : [Errno 12] Cannot allocate memory from python subprocess. 调用

python - 后台进程 subprocess.Popen with Pipe

Python - 无法调用系统命令

functional-programming - 如果我在 OCaml 中使用列表创建图形数据结构/算法会有效吗?

ocaml - OCaml 中是否使用了 "open-ended list"和 "difference-list"?

node.js - OCaml/Node.JS 上的 Lwt.async 和 Lwt_main.run 有什么区别?

utf-8 - OCaml websocket "Invalid UTF8 data"

带引号和反斜杠的 Python subprocess.Popen

ocaml - 让利用数据依赖性来增加并行性吗