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

Greeting monks, I have a module that serves as a manager for a server (piece of software, not a computer) -- it can start or stop the server, retrieve configuration and status information, etc.

I'd like to arrange things so that if the server is started and the perl process managing it crashes then the server get's shut down, too. The easiest way to do this is through an END block, but I what I want to do is to have the END block 'active' (that is, it will execute on shutdown) only if the server is running. So I'd like to put the END block in place after successful server startup and then remove it after successful server shutdown -- that is after perl code successfully shuts it down on purpose.

I've found the CPAN module Manip::END, but wonder if there is a better solution out there?

--DrWhy

"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

Replies are listed 'Best First'.
Re: Manipulating END blocks
by CountZero (Bishop) on Sep 13, 2007 at 19:14 UTC
    Why don't you just maintain a flag somewhere (either in a variable if your manager program remains active throughout; or in a file if this program is not always active) and check that flag in the END block so you know whether to call the shutdown code or not.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Manipulating END blocks
by ikegami (Patriarch) on Sep 13, 2007 at 20:01 UTC

    Why don't you use a flag instead of messing with internal structures?

    my $server_running = 0; END { if ($server_running) { ... } }

    When appropriate, toggle $server_running.

    ( Oops, I didn't notice someone had already replied. )

      Because I like messing with Perl's internal structures ;)

      Actually I realized the same thing after I posted this question, and that's how I'm going to implement this in this case.

      I still would like to hear other's thoughts on the general question of how best to manipulate END routines when there's not a more straightforward way to accomplish the same effect.

      --DrWhy

      "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

        Well, nothing is stopping you from eval'ing some code that defines the END block you want. That's probably the simplest way to do it.