I recently inherited some code that someone else had written.
I discovered that everywhere in the code that a directory was opened for reading, it was never closed because the original developer had a syntax problem - he was using the close
function to try to close a directory handle instead of the closedir
function.
The code was something like this:
opendir( DIR, $dir ) or die "Cannot open $dir: $!\n";
@files = readdir( DIR );
close( DIR );
(Which is another good point that is made in Perl Best Practices (pages 208,278) about checking the return of the close
function. If the return of close
were checked in this case, it would be failing with "Bad file number".)
I've since changed this to closedir
, but it made me start wondering: Since the directory handle was never closed, what are the negative implications to keeping a directory handle opened for a long duration?
This program is larger (3,500 lines of code), runs for a while (5-10 minutes), and multiple instances of this program are running at the same time. In the case of this directory in the example above, $dir
is the same value for all instances. If 10 instances of this program were running at the same time, they all held an open directory handle against the same directory for 5 minutes or longer. I'm sure Perl is closing the directory handle automatically when the program finishes, but best practice says to close it as soon as possible.
It is more obvious to me where leaving file handles open can cause problems (especially for file handles that are open for writing), but what bad things can happen by not closing a directory handle?
The reason I am asking is because there has been an odd circumstance where this program was trying to create a file (in the directory defined by $dir above). The filename had the PID embedded in it, so it is a smaller chance that the file could already be there, but Perl was unable to open the file for writing, because it said it already existed. When we looked in the directory, that file did not exist. I am wondering if all of the open directory handles on this directory could cause such a problem?
I'm not sure if the OS makes a difference, but this program is running on AIX.
Thanks in advance, and happy Friday!