http://www.perlmonks.org?node_id=378033

bschmer has asked for the wisdom of the Perl Monks concerning the following question:

Good day monks. I have a bit of a head-scratcher that I haven't had much luck with so I hope that the collective mind of the monks can be of some help.

The problem is this, I have a script that starts with some filehandles already open which seem to be inherited via fork and/or exec and these file handles point to files not on the local filesystem which causes some pain when the remote file system goes out to lunch or the local system is rebooted. The annoyance is that I don't use these files in my script at all, so I'd just like to close all files other than STDIN, STDOUT and STDERR. Here's the code that was my attempt:

opendir(DH, "/proc/$$/fd"); while (my $item = readdir DH){ next if ($item =~ /\.\.?/); my @sinfo = stat("/proc/$/fd/" . $item); my $mode = $sinfo[2]; printf("Item is $item: %o\n", $mode); my $fh = FileHandle::fdopen($item, O_RDWR) || warn "Could not dup +$item"; print Dumper($fh); close($fh); } closedir(DH); opendir(DH, "/proc/$$/fd"); while (my $item = readdir DH){ next if ($item =~ /\.\.?/); print "Item is $item\n"; } closedir(DH);
This doesn't do the jobs since the 2nd opendir set prints out all of the same file descriptor numbers that exist at the beginning.

I'd be grateful for any suggestions.