ocaml-core equivalent of Unix.create_process

454 views Asked by At

I'd like to port the following command from Unix library to Jane Street's Core.Std.Unix library.

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

That is, I have an executable exec and arguments args and want to run the process using the same in/out/error channels as the current process.

I can get close with Core.Std.Unix.create_process ~exec:exec ~args:args, but can't figure out how to connect the stdin,stdout,stderr returned by this function from core with the file descriptors used by the current process.

2

There are 2 answers

1
ivg On BEST ANSWER

You can dup2 the returned descriptors to your current descriptors, but I'm not sure that this would work.

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

But there is another solution, that maybe applicable. Consider using just Unix.system, it should work just out of box.

0
dxue2012 On

I'm not sure if I understand your question correctly, but if you just want to use the same channels as the current process, take a look at fork_exec in Core.Std.Unix:

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

According to the docs,

fork_exec ~prog ~args ?use_path ?env () forks and execs prog with args in the child process, returning the child pid to the parent.