Fortran: pipe to program

北战南征 提交于 2019-12-11 01:28:10

问题


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.


回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/37763832/fortran-pipe-to-program

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