Note: the functions in this library have been merged in the ExtUnix project. Therefore this library will not receive further enhancements.

What is OCamlFd

OcamlFd is an extension library for the OCaml language, providing miscellaneous utility functions involving UNIX file descriptors. Currently, the following functions are implemented.


Many system calls receive paths or filenames as parameters when they should require file descriptors (FDs) to avoid race conditions. The following code has at least one race condition: the file might not exist when Unix.openfile is called.

    let filename = "/foobar" in
    if Sysfile_exists filename then
      Unix.openfile filename [Unix.O_RDONLY] 0
      raise Exit

Handling FDs rather than file names also allows cleaner, better code. For example, when a daemon forks to create a chrooted process that will exec another binary, not all code can be placed in the parent process, where it should be, because one cannot chroot the new process before calling exec if the binary isn't inside the jail. This becomes possible with Fd.fexecve.

It's true that FD system calls are not standard-supported. It happens because the standards were written to document what Unix is, not what it's going to be. Unix is a very old operating system and has its faults; we should write new code without old pitfalls.

Some of the FD functions are already available in OCaml's Unix module, for example: fchmod, fchown and ftruncate. Unfortunately, not all FD system calls are available in every platform. For example, Linux does not currently support fchroot, while systems which are not based on glibc do not support fexecve.

FDs are so flexible that they allow one having fake FDs. See function sandbox.newstream for an example. FDs also allow a userland application executes very fast copies among FDs, what may bring some kernel modules to user space without serverely punishing performance (See system calls sendfile(2), vmsplice(2), splice(2), tee(2)). These functions will be implemented in OCamlFd some time down the line.

Installing OcamlFd

These instructions assume you have Oasis installed.

  $ make configure
  $ make
  # make install

See the INSTALL file for more details.


Andre Nathan <andre at digirati dot com dot br>

Michel Machado <michel at digirati dot com dot br>



OCamlFd is licensed under the LGPL version 2.1.


The ocaml-fd repository is available on Github.