I am working on some code which is the back-end for a tool. This tool creates all its output in a fixed directory. Now suppose at any time a client wants to kill all its applications, then all files should be deleted. So I use the system command (rm -rf) to remove the directory, but files which are open are not deleted, and hence the directory is also not deleted. How can I do this smartly?
One option seems to be to use a table maintaining all the open files and closing them all before firing rm -rf on the directory. However, this may slow down the whole application.
Another option I explored is using lsof to find a list of open files and close them all before rm -rf.
An additional constraint on my issue is that I have open several different files in a process, and one of them is in use by another process. Using the above methods, if I close all the file descriptors and try to delete the directory, logically it should not be deleted because there are still files opened by another process.
Any suggestions would be appreciated.
I think using a script is a good idea for your instance, and Coren’s answer is precise. That being said, I’ve seen programs just loop through a substantial range of file descriptors to close all of them. It has the potential for error if you have more than the range you loop through, but something like this shouldn’t hurt an application if you’re intending to close all your descriptors, provided they are within this limit:
In order to have this done before your application exits, you can set a signal handler, as mentioned and linked by Coren. Make sure if you use signals and a handler that you do as little as possible in the signal handler, i.e. just set a flag and have your program do its cleanup.
Edit: Also, this answer from another post on StackOverflow gives both examples of how to do this (#3 is like Coren’s and is for Linux), but also has a couple of links to actual source code that handle this stuff. You might want to check it out!