2
votes

Is there any possibility to launch an external program from Fortran and write something to this programs standard input?

I know e.g. of gfortran's SYSTEM but there is no such option.

2

2 Answers

3
votes

As you have noticed, GFortran does not have anything like the pipe()/fork()/exec() functions builtin.

If you're on Linux or some other Unix-like system you could do something like

  1. execute_command_line("mkfifo /path/to/fifo")

The mkfifo command creates a named pipe, that is, a pipe that also has a name in the filesystem.

  1. open(newunit=plot_unit, file="/path/to/fifo", access="stream", format="formatted")

  2. execute_command_line("gnuplot < /path/to/fifo")

So the idea is that you can then open the FIFO like a normal external unit in GFortran, then execute gnuplot with standard input connected to the FIFO.

You might need to exchange the order of #2 and #3 in case this deadlocks. But some minor variation of the above should work (I've used it to connect to one Fortran program from another).

2
votes

Firstly, if you're using a relatively recent compiler you should be able to use execute_command_line (part of the f2008 spec) instead of system (compiler extension). This launches a command using the C library's system call which uses the sh shell on nix and cmd.exe on Windows (see here). As such you can use standard input redirection type approaches to connect to stdin of the launched program, but it may not be suitable for more complicated use.

The following example shows a simple example

program stdIn
  implicit none
  character(len=20) :: cmd, args
  character(len=50) :: fullcmd
  cmd = "bc"
  args = "1+2"
  fullcmd = cmd//" <<< "//args
  print*,"Running ",fullcmd
  call execute_command_line(fullcmd)
end program stdIn

Which should output

 Running bc                   <<< 1+2
 3