Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Cron Jobs That Run For Too Long

by sgifford (Prior)
on Dec 20, 2005 at 20:02 UTC ( #518173=note: print w/replies, xml ) Need Help??

in reply to Cron Jobs That Run For Too Long

On Unix, there are three common ways to solve this.

The first way is to have a lockfile that's always around. When your script starts, it tries to lock that file with flock; if it's already locked it exits, otherwise it does its work. The OS will automatically remove the lock when the process exits, even if it crashes or is killed.

The second way is to write the PID of the process into the lockfile. Then when another copy starts up, it checks if the lockfile exists, and if so it reads the PID and verifies that that PID is still running and is actually itself. If it finds that the process is no longer running, it just creates a new lock file and goes on. When the process finishes it removes the lockfile.

The third way is to get a list of all processes, and see if any of those are executing that script. If so, exit.

I generally favor the first of these, because it's easy and efficient.

Replies are listed 'Best First'.
Re^2: Cron Jobs That Run For Too Long
by ruoso (Curate) on Dec 20, 2005 at 22:07 UTC

    Just a note, adding to what sgifford said...

    I've seen some scripts around listing /proc to check if the process is still running. I prefer to use a kill 0 on the proccess...

    And I, personally, prefer the second way because it can be used for lockfiles even if the only place you can write the lockfile can't provide locking, or the locking isn't reliable (NFS)

      But wait, it gets better again!

      You know how you can have that nifty __DATA__ block at the end of your script? It turns out you can lock that too :)

      I've used this a number of times and it works just great.


      use strict;
      use Fcntl 'LOCK_EX', 'LOCK_NB';

      unless ( flock DATA, LOCK_EX | LOCK_NB ) {
          print STDERR "Found duplicate script run. Stopping\n";




      This exists to allow the locking code at the beginning of the file to work.

        hey, that's really nice.
        11 years later this is still brilliant.
        this works great!!! can you give explenations on the __DATA__ part? I dont have a clue what is this for... Roy

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://518173]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2018-06-23 09:26 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.