How to get the name of a file acting like stdin / stdout?

I had the following problem. I want to write a program in Fortran90 that I want to write like this:

./program.x < main.in > main.out 

In addition to "main.out" (whose name I can set when the program is called), secondary outputs should be written, and I wanted them to have the same name for "main.in" or "main.out", (they actually are called "principal"); however, when I use:

 INQUIRE(UNIT=5,NAME=sInputName) 

The contents of sInputName becomes "Stdin" instead of the file name. Is there a way to get the name of the files associated with stdin / stdout when the program is called?

+3
source share
2 answers

Unfortunately, the i / o redirect point is that you do not know what I / O files are. On unix-based systems, you cannot look at command line arguments, since < main.in > main.out actually processed by the shell, which uses these files to configure standard input and output before calling your program.

You must remember that sometimes standard input and output are not even files, as they can be a terminal or a pipe. eg.

 ./generate_input | ./program.x | less 

Thus, one solution is to redesign your program so that the output file is an explicit argument.

 ./program.x --out=main.out 

Thus, your program knows the file name. The cost is that your program is now responsible for opening (and possibly creating) a file.

However, on Linux systems, you can really find where your standard file descriptors point from the special / proc file system. There will be symbolic links for each file descriptor.

 /proc/<process_id>/fd/0 -> standard_input /proc/<process_id>/fd/1 -> standard_output /proc/<process_id>/fd/2 -> standard_error 

Sorry, I don’t know fortran, but the way to check psudeo code to check the output file could be:

 out_name = realLink( "/proc/"+getpid()+"/fd/1" ) if( isNormalFile( out_name ) ) ... 

Keep in mind what I said earlier, there is no garauntee, it will be a regular file. It can be a terminal device, a pipe, a network socket, anything ... In addition, I do not know what other operating systems work on other than redhat / centos linux, so it may not be so portable. More diagnostic tool.

+6
source

Maybe the get_command and / or get_command_argument built-in routines can help. They were introduced in fortran 2003 and either returned the full command line that was used to invoke the program or the specified argument.

0
source

Source: https://habr.com/ru/post/1206259/


All Articles