Execing Processes in Co-array Fortran

Our example demonstrates how to execute external processes in Co-array Fortran. This is useful when we need to completely replace the current Fortran process with another (perhaps non-Fortran) one.

program exec_process
  use iso_fortran_env
  implicit none

  character(len=256) :: command
  integer :: status

  ! For our example, we'll execute the 'ls' command. 
  ! In Fortran, we don't need to look up the path to the binary.
  command = "ls -a -l -h"

  ! In Fortran, we use the EXECUTE_COMMAND_LINE subroutine to run external commands.
  ! This is similar to the syscall.Exec function in other languages.
  call execute_command_line(command, wait=.true., exitstat=status)

  ! Check if the command execution was successful
  if (status /= 0) then
    write(error_unit,*) "Error executing command. Status: ", status
    stop
  end if

end program exec_process

When we run our program, it will be replaced by the output of the ls command:

$ gfortran exec_process.f90 -o exec_process
$ ./exec_process
total 16K
drwxr-xr-x  4 user user 4.0K Oct 3 16:29 .
drwxr-xr-x 91 user user 4.0K Oct 3 12:50 ..
-rw-r--r--  1 user user  420 Oct 3 16:28 exec_process.f90
-rwxr-xr-x  1 user user 8.0K Oct 3 16:29 exec_process

Note that Co-array Fortran doesn’t offer a classic Unix fork function. However, the EXECUTE_COMMAND_LINE subroutine covers most use cases for executing external processes.

In this example, we’ve used the EXECUTE_COMMAND_LINE subroutine, which is part of the Fortran 2008 standard. This subroutine allows us to execute shell commands from within our Fortran program. The wait=.true. argument ensures that our program waits for the command to complete before continuing, and the exitstat argument captures the exit status of the command.

Unlike in some other languages, Fortran doesn’t require us to explicitly set up environment variables or argument lists for the external command. The command is simply passed as a string to EXECUTE_COMMAND_LINE.

Remember that the exact output you see when running this program will depend on the contents of the directory where you run it.