Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
The stupid question is the question not asked
 
PerlMonks  

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 test.pl --> should run if there is no test.pl running. $ perl test.pl ---> should abort if there is a test.pl running alread +y. $ perl test.pl --test --> should run even if test.pl is already runni +ng. $ perl test.pl --test --> should abort if there is a (test.pl --test) + running as well.
    So, I am thinking of just creating a new script for (test.pl --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?
  • Comment on Conditional Lock File
    Select or Download Code
    Re: Conditional Lock File
    by roboticus (Canon) on Feb 02, 2011 at 19:53 UTC

      bichonfrise74:

      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!";

      ...roboticus

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

        Thanks. Your suggestion worked perfectly.

    Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Node Status?
    node history
    Node Type: perlquestion [id://885819]
    Approved by broomduster
    help
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others avoiding work at the Monastery: (5)
    As of 2014-04-20 07:36 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      April first is:







      Results (485 votes), past polls