How do I find all the open files in a process (from inside itself)?
This seems useful to know after a fork()
(before exec()
).
I know of the existance of getdtablesize()
and the more portable sysconf(_SC_OPEN_MAX)
, but it seems inefficient to attempt closing every valid file descriptor, whether there's an open file behind it or not. (I am also aware of the dangers of premature optimisation, this is more about aesthetics I guess :-)
When dealing with multiple files, you may want to use the File → Close All (Shift-Ctrl-W) menu item.
Description. fclose( fileID ) closes an open file. fclose('all') closes all open files.
If you want to find only close the open file descriptors, you can use the proc filesystem on systems where it exists. E.g. on Linux, /proc/self/fd will list all open file descriptors. Iterate over that directory, and close everything >2, excluding the file descriptor that denotes the directory you are iterating over.
The script to cause Net Files to close all open files is: for /f “skip=4 tokens=1” %a in ('net files') do net files %a /close. Drop to a command prompt, cut and paste this command into your command window, and press [Enter]. This will cause every file on your server to close, so use extreme caution when running it.
If your program will be calling fork
and exec
, you really should open all file descriptors with the O_CLOEXEC
flag so you don't have to manually close them before exec
. You can also use fcntl
to add this flag after a file is opened, but that's subject to race conditions in multithreaded programs.
It may sound inefficient to attempt to close all file descriptors, but it actually is not that bad. The system call implementation to lookup a file descriptor should be fairly efficient if the system is any good.
If you want to find only close the open file descriptors, you can use the proc filesystem on systems where it exists. E.g. on Linux, /proc/self/fd will list all open file descriptors. Iterate over that directory, and close everything >2, excluding the file descriptor that denotes the directory you are iterating over.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With