stdlib icon indicating copy to clipboard operation
stdlib copied to clipboard

Subroutines to get list of opened units and connected files and to close them

Open Beliavsky opened this issue 2 years ago • 1 comments

I suggest that stdlib have a subroutine that returns properties of files that are open

subroutine opened_units(units,files,actions,accesses,forms)
integer, intent(out), optional :: units(:)
character (len=*), intent(out), optional :: files(:), actions(:), accesses(:), forms(:)
end subroutine opened_units

with arguments corresponding to attributes specified in a read statement and a subroutine that closes opened units.

In 2010 Steve Lionel wrote in response to a question at the Intel Forum

"There is no option to close all open files, nor is there a convenient way to get a list of units that are open. (You can loop from 0 to 21473642(or something like that) and use INQUIRE (UNIT=n,OPENED=) to see if a unit is opened, but I don't recommend that.

I agree with the suggestion that you keep track of the unit numbers you use to open files."

Beliavsky avatar Nov 20 '21 13:11 Beliavsky

Such a routine is possible on most GNU-LInux and Unix systems (we have a proprietary one), you can see how it is done by looking at the code for lsof(f); in some cases it is quite easy by looking in ./proc/$$/fd; and if you open files with newunit most compilers (certainly not part of the standard) sequentially open them from -2 to -N so unless you close a lot of files you do not have to scan to -(huge(0)-1) with INQUIRE, but I have no idea what is possible on other platforms. It is a very odd (in my mind) reason we need that though. What is the use case? This used to be easier when LUNs were all positive and most compiler had a limit of 104 or 99; but that is not common anymore although I still have routines for checking a range of LUNs, but those are rarely used anymore (one common variant was to look for an unused LUN, but OPEN(NEWUNIT=... pretty much makes that obsolete unless you want to restrict yourself to positive LUNs; maybe because you want unnamed files to be fort.NNN instead of fort.-NNN or for other odd reasons (unnamed non-scratch files are non-standard but universally supported as far I know; but a bad idea in my mind in general). Making a wrapper around OPEN and/or asking for or asking for a feature in Fortran seems easier (that is, keep track of it yourself, which I have done with functions before, with a "NEWUNIT" function instead of an option that remembers returned values if wrapping OPEN() is too complicated); but there are system utilties on some platforms for querying this. I would like a standard INQUIRE-like command that returned the traceback, high-water memory use, and other things procedures like getrusage(3c) return myself (some compilers have that as an extension).

urbanjost avatar Nov 20 '21 18:11 urbanjost