为什么open_process_full没有返回我运行的外部进程的stdout内容?

时间:2014-11-17 21:09:44

标签: ocaml

我想运行一个外部程序并从其stdout收集数据。我试着做了

let () =
  let (sout, sin, serr) = Unix.open_process_full "echo" [|"echo"; "hello"; "world"|] in
  let line = input_line sout in
  Printf.printf "read \"%s\"\n" line

但我得到一个空字符串:

 read ""

我原本希望得到

 read "hello world"

如果我使用open_process_in而不是open_process_full,我注意到我得到了所需的结果。他们为什么表现不同?

let sout = Unix.open_process_in "echo hello world" in

1 个答案:

答案 0 :(得分:1)

open_process_full的第二个参数是环境变量,而不是argv。如果要使用argv数组调用子进程,请改用create_process

let (pr1, pw1) = Unix.pipe () in
let (pr2, pw2) = Unix.pipe () in
let _pid = Unix.create_process "/bin/echo" [|"echo"; "hello"; "world"|] pr1 pw2 Unix.stderr) in
let echo_in = Unix.out_channel_of_descr pw1 in
let echo_out = Unix.in_channel_of_descr pr2 in
let line = input_line echo_out in
Printf.printf "read \"%s\"\n" line