3

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

#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吗?

4

1 回答 1

2

用于Lwt_process.shell制作正确的命令,在您的情况下,正确的命令如下:

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

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

于 2016-03-21T21:00:13.973 回答