Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing all open files in a process

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

like image 857
Magnus Avatar asked Aug 22 '09 07:08

Magnus


People also ask

How do I close all open files?

When dealing with multiple files, you may want to use the File → Close All (Shift-Ctrl-W) menu item.

Which function is used to close all open files?

Description. fclose( fileID ) closes an open file. fclose('all') closes all open files.

How do I close all open files in Linux?

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.

How do you close all files in CMD?

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.


2 Answers

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.

like image 178
R.. GitHub STOP HELPING ICE Avatar answered Sep 20 '22 06:09

R.. GitHub STOP HELPING ICE


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.

like image 25
Martin v. Löwis Avatar answered Sep 22 '22 06:09

Martin v. Löwis