Safe Systems Programming

Posted in ocaml, programming

Rust seems like a good choice for systems programming. See this recent post for an example of the safety afforded by using Rust instead of C. Another language that deserves consideration is OCaml, where forking a process looks like this:

match Unix.fork () with
| 0 -> (* child process *)
| pid -> (* parent process *)

Short and sweet, but besides being pleasant to read, is this code actually safe? What if Unix.fork returns -1? Well, it can’t. Unix.fork calls a C function that starts with the following lines of code:

int ret;
ret = fork();
if (ret == -1) uerror("fork", Nothing);

That is, if the actual system call fails, Unix.fork raises an exception that may terminate our program. We can’t accidentally kill -1 because pid is guaranteed to be a valid process ID.

If this sounds interesting, I recommend checking out Unix Systems Programming in OCaml.