If you are used to the Unix programming with C, then almost the same concepts apply to OCaml using the Unix module, with slightly different syntax for function calls and arguments.
It is pretty straight forward if you have already done some system programming in C before, to compile you should add unix.cma to the arguments of ocamlc.
Example 1: fork, getpid and getppid :
This example shows how to do a simple fork to create a new process, then each process prints its pId to the console, here we cannot ensure which one will print first, the parent or the child. Here we use the usual function fork, getpid to get the ID of the current process and getppid to get the parent process.
Example 2, wait:
To ensure that the child process finish before its parent we use the wait system call, which returns the id of the finished process and the status code returned from the process.
As you see, the child exits with the code 13, the parent calls wait to wait for its unique child created with fork, then reads the returned code, note that OCaml will generate a warning here because we just check for WEXITED (we know it will exit normally) but we omit WSIGNALED and WSTOPPED. In C you don’t have this flexibility of warnings which can brings you a lot of trouble.
Exemple 3, exec*:
This example demonstrates how to use the exec* calls, these methods replaces the core of the process with the new code of the command to be executed thus the function never returns, when the function fails, an exception is thrown, check the specifications here.
Here we fork and replace the child code with the ls command’s, here is the output