Search code examples
bashperlfileexceptiondie

What happens as a perl script ends?


This question is specific to perl, in the context that I am specifically wondering what happens to file handles (both operated on and not) when at some point the script dies with the handles open.

So what operations occur as the execution comes to the final line of the script? Script level? Perl level? Shell level (e.g. bash)? System level (e.g. assume a modern *nix, such as Ubuntu)?

Here's what info I've found so far, though no direct answers:

Best practices for terminating perl scripts

Ensure custom code is run upon exit in perl

Why to close file handles in perl (sys buffers)

Perldoc on die and exit speak mostly of the functions themselves.


Solution

  • Perl uses a reference counting strategy for garbage collection. When a variable's reference count reaches 0, any applicable DESTROY method is called before releasing its memory to perl's memory management system.

    As your program terminates, its remaining variables will go out of scope and have their reference count decremented. This is the point at which your file handles will close.

    When perl is finished with its clean-up, it will exit back to the operating system, at which point its remaining resources will be returned to the OS, and its parent process (perhaps init or a shell) will be informed of its exit status.


    Where reference counting might go awry: If you create a data structure with circular references, none of the component variables will naturally have their reference count drop to 0 unless you either weaken one of the references or explicitly call its DESTROY method. In this case the variables will persist until program end, at which point perl will DESTROY and/or garbage collect everything regardless of its reference count.