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
Import the module unix
and link your Fortran application 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 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.'
else
! 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:
$ gfortran10 -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.
References
- fortran-unix: Fortran 2008 interface bindings to POSIX fork(2)
< OpenMP | [Index] | POSIX Threads > |