gFortran对睡眠的调用不会阻塞程序



我有最基本的Fortran程序:

program sleep
print*, "Sleeping"
call sleep(30)
print*, "Done"
end program sleep

我用gfortran sleep.f90(版本9.3.0(编译的。根据我从sleep文档中了解到的,这个程序应该睡眠30秒,即我应该看到";完成";在"打印"后30秒打印;睡觉";。这并没有发生:我看到两个print语句都会立即出现,这表明call sleep(30)不会以任何方式阻止我的程序。做call sleep(10000)没有任何区别。我正在Linux的Windows子系统(WSL Ubuntu 20.04(上编译和运行这个程序

因此,通过@roygvib在评论中提出的解决方案组合,解决了这个问题。主要问题是WSL(Ubuntu 20.04(环境中的sleep已损坏。第一步是用以下Python脚本替换损坏的/usr/bin/sleep

#!/usr/bin/env python3
import sys
import time
time.sleep(int(sys.argv[1]))

然后,Fortran程序被修改为对这个新的sleep可执行文件进行system调用:

program sleep
print*, "Sleeping"
call system("sleep 30")
print*, "Done"
end program sleep

直到WSL的下一次更新,这个黑客将不得不做。

sleep过程不是Fortran标准的一部分,并且不可移植。以下是一个解决方案,它可能适用于任何符合标准的Fortran编译器的所有系统:

module sleep_mod
use, intrinsic :: iso_fortran_env, only: IK => int64, RK => real64, output_unit
implicit none
contains
subroutine sleep(seconds)
implicit none
real(RK), intent(in) :: seconds ! sleep time
integer(IK)          :: countOld, countNew, countMax
real(RK)             :: countRate
call system_clock( count=countOld, count_rate=countRate, count_max=countMax )
if (countOld==-huge(0_IK) .or. nint(countRate)==0_IK .or. countMax==0_IK) then
write(output_unit,"(A)") "Error occurred. There is no processor clock."
error stop
end if
countRate = 1._RK / countRate
do
call system_clock( count=countNew )
if (countNew==countMax) then
write(output_unit,"(A)") "Error occurred. Maximum processor clock count reached."
error stop
end if
if ( real(countNew-countOld,kind=RK) * countRate > seconds ) exit
cycle
end do
end subroutine sleep
end module sleep_mod
program main
use sleep_mod, only: output_unit, sleep, RK
implicit none
write(output_unit,"(A)") "Sleep for 5 second."
call execute_command_line(" ") ! flush stdout
call sleep(seconds = 5._RK)
write(output_unit,"(A)") "Wake up."
end program main

你可以在这里在线测试:https://www.tutorialspoint.com/compile_fortran_online.php

相关内容

最新更新