Sleep
The Fortran standard does not include any routine for pausing a program for a given time. Most compilers, like GNU Fortran, provide a routine through extensions:
! sleep.f90
program main
implicit none
integer :: i
do i = 1, 10
print '(a)', 'zzz ...'
call sleep(2)
end do
end program main
GNU Fortran’s sleep()
routine pauses the process for the given
time in seconds. Other compilers may provide similar extensions. As an
alternative, a compiler-independent interface to the POSIX routine
sleep(3)
can be written, making the call compatible to all POSIX-compliant operating
systems.
POSIX
In order to sleep for less than a second, one might consider an ISO C binding interface to usleep(3), which pauses the process for a given interval measured in microseconds. The library fortran-unix includes the necessary Fortran interface binding. But we can instead just define an interface manually:
! example.f90
module posix
use, intrinsic :: iso_c_binding, only: c_int, c_int32_t
implicit none
interface
! int usleep(useconds_t useconds)
function c_usleep(useconds) bind(c, name='usleep')
import :: c_int, c_int32_t
integer(kind=c_int32_t), value :: useconds
integer(kind=c_int) :: c_usleep
end function c_usleep
end interface
end module posix
program main
use :: posix
implicit none
integer :: i, rc
integer :: t = 500 * 1000 ! 500 milliseconds
do i = 1, 10
print '(a)', 'zzz ...'
rc = c_usleep(t)
end do
end program main
Be aware that usleep(3) has been declared obsolete. It is recommended to use nanosleep(2), but a little more complex derived type binding is required then.
References
- fortran-unix: Fortran 2008 interface bindings to POSIX functions
< Date and Time | [Index] | Random Numbers > |