Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Conditional Lock File

by bichonfrise74 (Vicar)
on Feb 02, 2011 at 18:36 UTC ( #885819=perlquestion: print w/replies, xml ) Need Help??
bichonfrise74 has asked for the wisdom of the Perl Monks concerning the following question:

I would like to hear some advise on how to deal with this scenario. My goal or what I think I want to happen is this:

  • Run a script without arguments (main script) if the same script is not running.
  • Run a script with argument while the main script is running but not if there is a script with argument is running.

    Here is the code.
    #!/usr/bin/perl use strict; use Fcntl qw( :flock ); use Getopt::Long; GetOptions( 'test' => \my $option_test ); print "Running $0\n"; check_process() if ( ! defined( $option_test ) ); sleep 30; print "Running $0\n"; sub check_process { open( SELF, '<', $0 ) || die "Error: Cannot open $0 for locking - $!\n"; flock( SELF, LOCK_EX | LOCK_NB ) || die "Error: Another $0 is already running.\n"; return 1; }
    So, here is the flow that I want.
    $ perl --> should run if there is no running. $ perl ---> should abort if there is a running alread +y. $ perl --test --> should run even if is already runni +ng. $ perl --test --> should abort if there is a ( --test) + running as well.
    So, I am thinking of just creating a new script for ( --test), but the reason why I am hesitant to this is because the new script is almost 95% identical to the main script.

    Would this be the best course of action for this scenario?
  • Replies are listed 'Best First'.
    Re: Conditional Lock File
    by roboticus (Chancellor) on Feb 02, 2011 at 19:53 UTC


      It looks like you have most of it. All you'd need to do is pass in a different lockfile name if there's an argument vs. without one. Perhaps something like:

      my $lockfile = '/tmp/my.lockfile'; $lockfile .= '.with_arg' if $fl_has_arg; check_process($lockfile) and die "Already running!";


      When your only tool is a hammer, all problems look like your thumb.

        Thanks. Your suggestion worked perfectly.

    Log In?

    What's my password?
    Create A New User
    Node Status?
    node history
    Node Type: perlquestion [id://885819]
    Approved by broomduster
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (7)
    As of 2018-06-18 06:56 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (109 votes). Check out past polls.