Search code examples
ocamlocaml-core

ocaml-core equivalent of Unix.create_process


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.


Solution

  • 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.