Stop fortran program with non-zero exit status

21,126

Solution 1

The stop statement allows a integer or character value. It seems likely that these will be output to stderr when that exists, but as stderr is OS dependent, it is unlikely that the Fortran language standard requires that, if it says anything at all. It is also likely that if you use the numeric option that the exit status will be set. I tried it with gfortran on a Mac, and that was the case:

program TestStop
integer :: value
write (*, '( "Input integer: " )', advance="no")
read (*, *) value
if ( value > 0 ) then
   stop 0
else
   stop 9
end if
end program TestStop

While precisely what stop with an integer or string will do is OS-dependent, the statement is part of the language and will always compile. call exit is a GNU extension and might not link on some OSes.

Solution 2

I couldn't find anything about STOP in the gfortran 4.7.0 keyword index, probably because it is a language keyword and not an intrinsic. Nevertheless, there is an EXIT intrinsic which seems to do just what I was looking for: exit with a given status. And the fortran wiki has a small example of using stderr which mentions a constant ERROR_UNIT. So now my code now looks like this:

USE ISO_FORTRAN_ENV, ONLY : ERROR_UNIT
[…]
WRITE(ERROR_UNIT,*) 'There as an error of kind foo'
CALL EXIT(1)

This at least compiles. Testing still pending, but it should work. If someone knows a more elegant or more appropriate solution, feel free to offer alternative answers to this question.

Share:
21,126

Related videos on Youtube

MvG
Author by

MvG

Dr. Martin von Gagern. Studied computer sciences, obtained a PhD in mathematics, currently a Google site reliability engineer.

Updated on September 17, 2020

Comments

  • MvG
    MvG over 2 years

    I'm adapting some Fortran code I haven't written, and without a lot of fortran experience myself. I just found a situation where some malformed input got silently ignored, and would like to change that code to do something more appropriate. If this were C, then I'd do something like

    fprintf(stderr, "There was an error of kind foo");
    exit(EXIT_FAILURE);
    

    But in fortran, the best I know how to do looks like

    write(*,*) 'There was an error of kind foo'
    stop
    

    which lacks the choice of output stream (minor issue) and exit status (major problem).

    How can I terminate a fortran program with a non-zero exit status?

    In case this is compiler-dependent, a solution which works with gfortran would be nice.

  • astrojuanlu
    astrojuanlu over 9 years
    According to the standard, "At the time of termination, the stop code, if any, is available in a processor-dependent manner."
  • Vladimir F Героям слава
    Vladimir F Героям слава over 7 years
    STOP is a statement. EXIT() is a GNU extension and may not be available in other compilers.

Related