1

我正在尝试在 Ocaml 中为基于终端的应用程序构建一个新的前端。主要思想是使用 Lwt 生成一个新进程:

let cmd = shell "./otherterminalapp" in
let p = open_process_full cmd;

然后稍后将内容写入进程的标准输入,以在外部应用程序中执行命令。

 Lwt_io.write_line p#stdin "some command" >>= (fun _ -> Lwt_io.flush p#stdin)

当我从命令中读取结果时Lwt_io.read_line_opt. 我如何阅读直到没有任何行?我遇到的问题是我的程序只是在某个点挂起。当我阅读时read_line_opt,当我到达终点时,它似乎只是在等待重定向新输出的过程。

我该如何处理?

我正在尝试做的一个具体示例:(基于终端的应用程序是 ocamldebug)

程序源代码:

open Lwt
open Lwt_unix
open Lwt_process
let () =
  let run () =
    let cmd = shell "ocamldebug test.d.byte" in
    let dbgr = open_process_full cmd in
    (((((((Lwt_io.write_line dbgr#stdin "info modules") >>=
            (fun _  -> Lwt_io.flush dbgr#stdin))
           >>= (fun _  -> Lwt_io.read_line_opt dbgr#stdout))
          >>=
          (fun s  ->
             (match s with
              | Some l -> print_endline l
              | None  -> print_endline "nothing here! ");
             Lwt_io.read_line_opt dbgr#stdout))
         >>=
         (fun s  ->
            (match s with
             | Some l -> print_endline l
             | None  -> print_endline "nothing here! ");
            Lwt_io.read_line_opt dbgr#stdout))
        >>=
        (fun s  ->
           (match s with
            | Some l -> print_endline l
            | None  -> print_endline "nothing here! ");
           Lwt_io.read_line_opt dbgr#stdout))
       >>=
       (fun s  ->
          (match s with
           | Some l -> print_endline l
           | None  -> print_endline "nothing here! ");
          Lwt_io.read_line_opt dbgr#stdout))
      >>=
      (fun s  ->
         (match s with
          | Some l -> print_endline l
          | None  -> print_endline "nothing here! ");
         Lwt.return ()) in
  Lwt_main.run (run ())

如果您通常使用 运行ocamldebugtest.d.byte您会在终端中获得以下信息:

    OCaml Debugger version 4.03.0

(ocd) info modules
Loading program... done.
Used modules: 
Std_exit Test Pervasives CamlinternalFormatBasics
(ocd) 

当我执行上述程序时,我会打印以下内容:

    OCaml Debugger version 4.03.0

(ocd) Loading program... Used modules: 
Std_exit Test Pervasives CamlinternalFormatBasics

在这里它只是挂起......,我的程序没有退出。即使我在终端中执行 Ctrl-c/Ctrl-c,也会有一个活动的 ocamlrun 进程。然而,终端变得响应。

我在这里遗漏了一些明显的东西?

4

1 回答 1

3

调用Lwt.read_line_opt返回一个延迟值,该值将在将来确定为Some data一旦通道读取以换行符结尾的字符串,或者None通道是否关闭。如果存在文件结束条件,通道将关闭。对于常规文件,文件结束条件发生在文件指针到达文件末尾时。对于用于与子进程通信的管道,当对方关闭与管道关联的文件描述符时,就会出现文件结束条件。

ocamldebug程序不会关闭其输入或输出。它是一个交互式程序,准备好与用户进行无限时间的交互,或者直到用户通过点击Ctrl-D或使用quit命令关闭程序。

在您的场景中,您将info modules命令写入通道的输入。该进程以三行响应(其中每一行都是以换行符结尾的一段数据)。然后子进程开始等待下一个输入。您没有看到(ocd)提示,因为它没有被换行符终止。程序没有挂断。它仍在等待子进程的输出,子进程正在等待您的输入(死锁)。

如果你真的需要区分不同命令的输出,那么你需要在子流程输出中跟踪提示。由于提示不是由换行符终止的,因此您不能依赖read_line*函数族,因为它们是行缓冲的。您需要阅读所有可用字符并手动在其中找到提示。

另一方面,如果您真的不需要区分不同命令的输出,那么您可以忽略提示(实际上,您甚至可以将其过滤掉,以获得更好的输出)。在这种情况下,您将有两个并发的子例程 - 一个负责提供输入,另一个将读取所有输出并将其转储,而不实际携带数据的内容。

于 2016-12-12T13:14:59.637 回答