in reply to how to close all files

Tricky. Here's a non-portable way to do it.

First, get a list of file descriptors. On many Unix systems, you can use lsof for that, or look in the /proc filesystem (which will have a different format on different OSses). On my system, I can do:

my @fds = `ls /proc/$$/fd`; chomp @fds;
Now you have a list of filedescriptors. Unfortunally, you cannot use Perl's close with just the filedescriptor. But don't despair, Perl does give you access to the system calls. syscall is unknown to many people, but it's powerful. On a Unix system, the following ought to work:
require 'syscall.ph'; # May have to run h2ph first. for my $fd (@fds) { syscall(&SYS_close, $fd) == -1 or die $!; }
Frankly, I rather keep track of my filehandles. ;-)

Replies are listed 'Best First'.
Re^2: how to close all files
by massa (Hermit) on Oct 23, 2008 at 13:46 UTC
    I think this could not flush the last-written buffer on files... Maybe
    exec env => $^X, $0, '--secret-forked-flag', @ARGV
    would work better, as perl closes all files on exec??
    []s, HTH, Massa (κς,πμ,πλ)
      From perldoc -f fork:
      Beginning with v5.6.0, Perl will attempt to flush all files opened for output before forking the child process, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the "autoflush()" method of "IO::Handle" on any open handles in order to avoid duplicate output.
      Forking cannot easily be replaced with an exec of itself. The process may have done extensive computation for instance. Furthermore, after an exec(), you still have open file handles: STDIN, STDOUT and STDERR.
      Why do you care about flushing the last write? Presumably the reason for the closes is to leave the control of all the open files to the parent.

      As for what JavaFan suggests, keeping track of open file descriptors when you know you might need to close them all at the same time is painful, but probably the wisest. Simply finding the open descriptors and closing them may or may not be a good idea. Some open descriptors may be within the context of included modules, and simply closing the descriptor without invoking the 'normal' close/disconnect/exit method might not produce the expected/desired results.

Re^2: how to close all files
by mr_mischief (Monsignor) on Oct 23, 2008 at 23:47 UTC
    syscall() is one way. See Re: how to close all files where BrowserUk uses the core POSIX module to close by descriptor, though. It's probably the more portable choice for this task.