Moonshile
Moonshile

Reputation: 37

In OCaml, how to get stdout string from subprocess?

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?

Upvotes: 1

Views: 2058

Answers (1)

ivg
ivg

Reputation: 35210

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.

Upvotes: 3

Related Questions