这是一个使用 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/