in reply to self detecting script

I'd use a Lockfile.
As an idea: Open the file for writing, lock it (or stop here, if it is already locked), write your PID in it (I like to know the pid's of running processes) and unlock (and close of course) it when you're done.

That's just an idea. If someone knows con's about this technique, please tell :)

ruoso's suggestion seems much more verbose.

Ordinary morality is for ordinary people. -- Aleister Crowley

Replies are listed 'Best First'.
Re^2: self detecting script
by gri6507 (Deacon) on Sep 15, 2005 at 18:47 UTC
    The only problem with this type of an approach is if the guts of your script are long and complex, having multiple exit points or failure modes, such as "do this or die" or "do this or croak". It gets even worse if you are using some other module which has a "do or die" type function. This way your program will exit without cleaning up the lockfile.

    So, the obvious solution to this is to put the lockfile cleanup into an END block. However, even that will not work all the time. For example, if you are using a module which was compiled from an XS and that module takes a core dump, you will leave the lockfile behind.

    All this is to say that lockfiles have their weaknesses. One way to overcome these flaws is by trying to run your program and checking the presence of the lockfile for, say, average duration of script times a factor of 2. This way, if the lockfile still exists, then it must be a stray file which should be deleted so the script can run.

      Won't Perl release open file handles when it exists? Even in a die or croak when the script exists it will lose the lock.

      -- More people are killed every year by pigs than by sharks, which shows you how good we are at evaluating risk. -- Bruce Schneier
        It's not so much that the filehand is left open when the exit event happens. Usually when the lockfiles are created the script simply writes its pid to the file and closes the filehandle to flush the file. Then when the script exists, the lockfile is deleted. However, if an unexpected exit happens, then the lockfile will still be around.
        Yes. If you actually flock the file, that lock will go away when the perl process exits, though the file itself will not.
      Good points, thanks. I think the problem with dying scripts can be striked by checking the saved PID as ruoso suggested. Well, then one should be sure not to leave zombies, I'd guess.

      Ordinary morality is for ordinary people. -- Aleister Crowley