Question

I'm pretty new to OCaml and was trying to figure out how to call an external program from within OCaml.

I've been following the documentation here, and making the following call:

Unix.execv "cat text_file";;

This returns the following:

string array -> 'a = <fun>

How exactly do I access the returned anonymous function?

cat text_file is a simple attempt to print the contents of the file, the command I actually want to run is a bit more complex. However, I presume that if I can get this running, I should be able to get my real program running.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top