21

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.

MvG
  • 57,380
  • 22
  • 148
  • 276

3 Answers3

24

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.

M. S. B.
  • 28,968
  • 2
  • 46
  • 73
  • According to the standard, "At the time of termination, the stop code, if any, is available in a processor-dependent manner." – astrojuanlu Jul 02 '13 at 06:37
11

In addition to stop n, there is also error stop n since Fortran 2008. With gfortran under Windows, they both send the error number to the OS, as can be seen with a subsequent echo %errorlevel%. The statement error stop can also be passed an error message.

program bye
    read *, n
    select case (n)
        case (1); stop 10
        case (2); error stop 20
        case (3); error stop "Something went wrong"
        case (4); error stop 2147483647
    end select
end program
3

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.

MvG
  • 57,380
  • 22
  • 148
  • 276