in reply to Perl file handles

Is there a way to get a perl script to close all files handles and exit cleanly no matter what?

exit

Seems like perl still realizes that somewhere down the line the java app is still running. And won't let me rename or change StartJava.pl.

Perl has an open file handle to the script if the script contains a __DATA__ or __END__.

While Perl gives up it's shared and exclusive lock on the file (allowing the file to be read and written by others), it doesn't give up the delete lock on the file (preventing others from deleting or renaming the file).

The solution is simple. As Corion told you in the CB, simply do close(DATA);

#!perl -l system qq{del "$0" >nul 2>&1}; print(-e $0 ? "not deleted" : "deleted"); close(DATA); system qq{del "$0" >nul 2>&1}; print(-e $0 ? "not deleted" : "deleted"); __DATA__
not deleted deleted

Even though the perl process and the cmd prompt which started it have both closed.

That's not possible. A process automatically relinquishes its file handles and file locks when it exits. Something else must have a lock on the file if Perl isn't running.

Update: Added code.

Replies are listed 'Best First'.
Re^2: Perl file handles
by Anonymous Monk on Mar 06, 2009 at 19:01 UTC
    I appreciate the response, and I guess I did not catch the mention of using close(DATA). All CB showed me was "All is quiet".

    That being said, the above code and it doesn't work.

    I use :

    system qq{$Command "$0" >nul 2>&1};

    close(DATA);

    Same as usual. File cannot be deleted or renamed.

      Wrong order. Closing DATA after the child has finished running will have little effect on the child.
        Ah! that did work.

        So, the idea is to close the DATA handle BEFORE you spawn the child, so the handle is not passed to it in the first place?

        I was thinking you closed the handle between the child being spawned and the parent process closing. But then I assume the child would still have a pointer back to the originating file?

        I am still unclear about how threading in perl works.