1

I'm working with OCaml and need to start a new process and communicate with it.

  1. If the subprocess terminated once it's called and produced some output, then how to retrieve the strings in it's stdout?

  2. What if the subprocess never terminates? That is, everytime given a string to stdin, it will produce a result to stdout, how to fetch the result?

1

1 Answer 1

3

Use Unix.open_process_in function. It will spawn a process and return an input channel, that will allow you to read data from the process.

If you want to wait for the process to terminate, you can just read all the data (i.e., wait until the process pipe returns EOF), and then close the channel, e.g.,

(* [run cmd] runs a shell command, waits until it terminates, and  
   returns a list of strings that the process outputed *)
let run cmd =
  let inp = Unix.open_process_in cmd in
  let r = In_channel.input_lines inp in
  In_channel.close inp; r

Working with non-terminating process is even easier.

You may also find interesting lwt library that has a very descent interface to multiprocessing. And async library is another asynchronous library that provide an excellent interface to multiprocessing. Although, this libraries are great, they are little bit advance, for simple cases standard Unix module is enough.

6
  • Is this using the Jane Street "Core" library? i.e.Stdio.In_channel.input_lines ocaml.janestreet.com/ocaml-core/latest/doc/stdio/Stdio/… ?
    – Anentropic
    Jan 29, 2022 at 10:49
  • Yes, the stdio library from the core suite. But the latest version of OCaml already has this module in its standard library.
    – ivg
    Jan 29, 2022 at 14:07
  • closest I could find is input_line in Pervasives, and then I guess have to write your own func to repeat that until they're all read
    – Anentropic
    Jan 31, 2022 at 10:39
  • 1
    Indeed, the stdio module will be introduced only in the next version of OCaml (which is currently in beta). So unless you have specific reasons not to install stdio with opam search stdio (don't hesitate to ask for help if you have trouble installing or using it), you can easily write your own function that inputs all lines from a file, here is the example stackoverflow.com/a/23456034/2625442
    – ivg
    Jan 31, 2022 at 16:38
  • 1
    for 4.14 and above (5.x including)
    – ivg
    Jan 31, 2022 at 17:12

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.