Sleep in Fortran

Brian Triplett picture Brian Triplett · Aug 3, 2011 · Viewed 10.1k times · Source

Does anyone know of an way to sleep for a given number of milliseconds in Fortran? I do not want to use non-portable system calls so anything intrinsic to Fortran or C libraries would be preferred.

Answer

M. S. B. picture M. S. B. · Aug 3, 2011

Using the Fortran ISO C Binding to use the C library sleep to sleep in units of seconds:

   module Fortran_Sleep

   use, intrinsic :: iso_c_binding, only: c_int

   implicit none

   interface

      !  should be unsigned int ... not available in Fortran
      !  OK until highest bit gets set.
      function FortSleep (seconds)  bind ( C, name="sleep" )
          import
          integer (c_int) :: FortSleep
          integer (c_int), intent (in), VALUE :: seconds
      end function FortSleep

   end interface

end module Fortran_Sleep


program test_Fortran_Sleep

   use, intrinsic :: iso_c_binding, only: c_int

   use Fortran_Sleep

   implicit none

   integer (c_int) :: wait_sec, how_long

   write (*, '( "Input sleep time: " )', advance='no')
   read (*, *) wait_sec
   how_long = FortSleep ( wait_sec )

   write (*, *) how_long

   stop

end program test_Fortran_Sleep