how to stop a fortran program abnormally

守給你的承諾、 提交于 2019-11-28 08:34:16

问题


When an exception occurs I would like to terminate abnormally my program. Right now, when an exception happens a write statement with an explanatory sentence is called, and then a stop statement is called.

I am debugging the program with idb (intel debugger), when the exception happens I get the write statement, but idb treats the program as terminated normally. I would like that when the exception happens the program is terminated abnormally and so that I can look to the memory with backtrace in the place where the exception happened.

I have tried changing stop in stop 1, so that a non zero value is returned, but this doesn't work

EDIT:

I have implemented the solution in one of the answer:

 interface
    subroutine abort() bind(C, name="abort")
    end subroutine
 end interface

 print *,1
 call abort()
 print *,2
end

with this solution I still do not get any backtrace when I am using ifort 13.0.1, but this works perfectly with ifort 14.0.2.

I have resorted to use idb instead of gdb, because often the latter cannot read the values of allocatable arrays in fortran.


回答1:


There are non-standard extensions for this. Gfortran uses backtrace() to print a backtrace anywhere, for the Intel's equivalent see the wander95's answer https://stackoverflow.com/a/38905855/721644.

In ifort and gfortran you can call the abort() subroutine and you will get backtrace if you used the -traceback (Intel) or -g -fbacktrace (gfortran) compiler option.

You could also call the C abort() directly using the C interoperability. (also non-standard and may not work in all circumstances):

  interface
    subroutine abort() bind(C, name="abort")
    end subroutine
  end interface

  print *,1
  call abort()
  print *,2
end



回答2:


With Fortran 2008 the ERROR STOP statement has been introduced. It's mainly used for Coarray Fortran programs to initiate error termination on all images.




回答3:


Found this old question by accident. If you want abnormal termination with the intel compiler, you can use the routine tracebackqq. The call sequence can be:

     call TRACEBACKQQ(string=string,user_exit_code=user_exit_code)

To quote the manual:

Provides traceback information. Uses the Intel® Fortran run-time library traceback facility to generate a stack trace showing the program call stack as it appeared at the time of the call to TRACEBACKQQ( )




回答4:


I've never used idb, I've only used gdb, so this might not work. I just put a read statement in at the error point, so that the program stops and waits for input. Then I can CTRL-C it, which causes gdb to pause execution, from which I can get a backtrace, move up and down the stack, look at variables, etc.



来源:https://stackoverflow.com/questions/30462371/how-to-stop-a-fortran-program-abnormally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!