I was once faced with a similar problem, but it occurred to me that prevention was better than cure. Code demonstrating that approach can be found here Re: Counting open files?
One world, one people
Comment on Re: Cleaning up filehandles and directoryhandles