Call an external program from within OCaml Call an external program from within OCaml unix unix

Call an external program from within OCaml


The first argument to execv is the program you want to run and the second is an array containing the arguments. Also, execv requires the full path to the program; you can use execvp to look up the program in the execution path. Furthermore the first argument to the program is the name of the program itself.So you want "/bin/cat" as the first argument, not "cat text_file", and [| "cat"; "text_file" |] as the second argument (or call execvp and pass "cat" as the first argument).

However, more often than not you actually want system, not execv.

Note that system allows you to pass a single string like you want and that execv (unlike system) never returns, i.e. once you call execv your program is done and the application you invoke takes over the process.


In addition to what sepp2k said, you might want to look into using create_process (for Unix.file_descr) or open_process (for channels). These functions do a fork/exec and redirect the i/o for the process. That way you can communicate with the process, which you can't do with system.

If you want to read the output of cat in your program, you can create a pipe using the pipe function, and then use the returned file_descrs for create_process.