On POSIX-compliant operating systems, fork(2) from unistd.h is used to spawn a new child process which can run simultaneously with and independently of the original parent process. Expensive calculations can be moved to a background process while the main process continues. The fortran-unix library provides the required Fortran 2008 interface bindings to fork(2) and wait(2).


Clone the fortran-unix repository and build the static library libfortran-unix.a:

$ git clone
$ cd fortran-unix/
$ make PREFIX=/usr/local OS=FreeBSD

On Linux, simply change PREFIX to /usr and OS to linux:

$ make PREFIX=/usr OS=linux

Import the module unix and link your Fortran application with libfortran-unix.a.


The example spawns a single child process with c_fork(). The child process just runs a blocking loop:

! fork.f90
program main
    use :: unix
    implicit none
    integer :: i, pid, rc

    pid = c_fork()

    if (pid < 0) then

        ! Fork failed.
        call perror('fork()' // c_null_char)

    else if (pid == 0) then

        ! Child process.
        print '(a)', '>>> child process running ...'

        do i = 1, 3
            ! Sleep for 1 second.
            rc = c_usleep(10**6)
            print '(">>> step ", i0, " ...")', i
        end do

        print '(a)', '>>> child process done.'


        ! Parent process.
        print '("--- waiting for child ", i0, " ...")', pid
        print '("--- child ", i0, " finished.")', c_wait(rc)

    end if
end program main

The parent process will wait until the forked child process is finished. Compile the example with:

$ gfortran11 -o fork fork.f90 libfortran-unix.a

Then, run the executable:

$ ./fork
--- waiting for child 16038 ...
>>> child process running ...
>>> step 1 ...
>>> step 2 ...
>>> step 3 ...
>>> child process done.
--- child 16038 finished.

Fortran Libraries