I recently inherited some code written by someone else.
I found that everywhere in the code that was open for reading the directory, it never closed because the original developer had a syntax problem - he used the close function to try to close the directory descriptor instead of closedir .
The code was something like this:
opendir( DIR, $dir ) or die "Cannot open $dir: $!\n"; @files = readdir( DIR ); close( DIR );
(This is another good point that Perl Best Practices (pages 208, 278) made about checking the return of the close function. If the close return was checked in this case, it will fail with a "Bad file number.")
Since then I changed it to closedir , but it made me start to wonder: since the directory descriptor has never been closed, what are the negative consequences for keeping the directory descriptor for a long time?
This program is larger (3500 lines of code), it takes some time (5-10 minutes), and several instances of this program work simultaneously. In the case of this directory in the above example, $dir is the same value for all instances. If 10 instances of this program were started at the same time, they all kept the open directory descriptor in the same directory for 5 minutes or longer. I'm sure Perl automatically closes the directory descriptor when the program ends, but it is best to close it as soon as possible.
It's more obvious to me that leaving open file descriptors can cause problems (especially for file descriptors that are open for writing), but what can happen if you don't close the directory descriptor?
The reason I ask is because there was a strange circumstance when this program tried to create a file (in the directory defined by the $ dir parameter above). The PID was embedded in the file name, so the likelihood that the file already exists is less, but Perl could not open the file for writing because it said that it already exists. When we looked in the directory, this file was not. I am wondering if such a problem may occur when working with the public directory of a directory in this directory?
I'm not sure if the OS matters, but this program works on AIX.
Thanks in advance, and happy Friday!