Fork

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).

fortran-unix

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

$ git clone https://github.com/interkosmos/fortran-unix
$ cd fortran-unix/
$ make freebsd

On Linux, instead run:

$ make linux

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

Example

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 c_perror('fork()' // c_null_char)

    else if (pid == 0) then

        ! Child process.
        print '(">>> child process running ...")'

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

        print '(">>> child process done.")'

    else

        ! Parent process.
        print '("--- waiting for child ", i0, " ...")', pid  ! Print PID of child process.
        print '("--- child ", i0, " finished.")', c_wait(rc) ! Wait for child (blocking).

    end if
end program main

The parent process will wait until the forked child process is terminated. The function interface c_wait() is blocking, and returns the PID of the child process once finished. Compile the example with:

$ gfortran12 -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