ocaml-core相当于Unix.create_process

时间:2014-07-30 08:18:01

标签: ocaml ocaml-core

我希望将以下命令从Unix库移植到Jane Street的Core.Std.Unix库。

Unix.create_process exec args Unix.stdin Unix.stdout Unix.stderr

也就是说,我有一个可执行文件exec和参数args,并希望使用与当前进程相同的输入/输出/错误通道来运行该进程。

我可以接近Core.Std.Unix.create_process ~exec:exec ~args:args,但无法弄清楚如何将此函数从核心返回的stdin,stdout,stderr与当前进程使用的文件描述符相连接。

2 个答案:

答案 0 :(得分:2)

您可以将dup2返回的描述符添加到当前描述符中,但我不确定这是否有效。

open Core.Std

let redirect ( p : Unix.Process_info.t ) : unit =
  let open Unix.Process_info in
  List.iter ~f:(fun (src,dst) -> Unix.dup2 ~src ~dst) [
    p.stdin,  Unix.stdin;
    p.stdout, Unix.stdout;
    p.stderr, Unix.stderr
  ]


let exec prog args : unit =
  let p = Unix.create_process ~prog ~args in
  redirect p

但还有另一种解决方案,可能适用。考虑只使用Unix.system,它应该只是开箱即用。

答案 1 :(得分:0)

我不确定我是否正确理解您的问题,但如果您只想使用与当前流程相同的渠道,请查看Core.Std.Unix中的fork_exec

val fork_exec : prog:string ->
                args:string list ->
                ?use_path:bool -> 
                ?env:string list -> 
                unit -> Core_kernel.Std.Pid.t

根据文件,

  

fork_exec~prog~args?use_path?env()forks和execs prog与子进程中的args,将子pid返回给父进程。