Unfortunately, this is a non-trivial problem. The lsof (list open files) utility may help however (if you're on a platform that has it...).  Or the Perl wrapper Unix::Lsof, written by a fellow monk.

Update: just a few more words on where this can get tricky.

Consider the not so untypical scenario of getting a long running forked process to dissociate cleanly in some webserver context, such that the (grand-)parent process may continue normally and serve subsequent requests. For this, it's necessary to close any file handles in the child that the grandparent would otherwise wait for to be closed (and thus block/hang). Now, with a regular CGI program this is still rather simple (by default, closing stdout/stderr is sufficient), but if you, let's say, have a FastCGI environment with persistent DBI/DBD connections to an Oracle database, things can get somewhat more involved. In particular because the respective modules and libraries under the hood may have opened files and sockets on their own, which are not under your immediate control. Also, as practice shows, brute force methods closing all handles may indirectly render the parent process non-functional...

That said, as long as your code has full control over which files are being opened, I agree it's usually best to just keep track of what needs to be closed (as has already been suggested elsewhere in the thread).


In reply to Re: how to close all files by almut
in thread how to close all files by eleron

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.