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

Wise Ones,

Is there a way to limit the number of copies of a given Perl script that can be executing, to for instance 5, at any given time?

R_D

Replies are listed 'Best First'.
Re: One hand on the Throttle
by bobf (Monsignor) on Nov 12, 2004 at 17:36 UTC
Re: One hand on the Throttle
by davido (Cardinal) on Nov 12, 2004 at 17:33 UTC

    One way is to maintain a counter file that is checked every time a script is run. If the counter file holds less than five, go ahead and increment it by one and continue execution. At the end of the script, decrement the counter file by one.

    This can get messed up if people kill-9 one of the scripts.

    One way to deal with the possibility of active processes being killed, thus fouling up the count file, is to use timestamp entries in the countfile. If you know that there is no way your script should take longer than 1 minute to run, and upon script startup, you find an entry in the file that is ten minutes old, remove that entry; it's a ghost.


    Dave

Re: One hand on the Throttle
by bart (Canon) on Nov 15, 2004 at 12:09 UTC
    I have an idea for an alternative approach, but I haven't actually tested it — I'm currently not even in a position to test it. Take a look at PPerl... If I interpret it correctly, there's one master copy of your script running, no matter how many you launch via a command line (shell). pperl in turn controls and launches forks of your running script.

    There is the problem of variables shared between all your scripts. Problem? No, in this particular case, you can make good use of it, and use one common variable to count how many copies are running. Each instance of your script should increment that variable, and decrement it when it exits. If there are too many already, exit immediately.

Re: One hand on the Throttle
by zentara (Cardinal) on Nov 14, 2004 at 12:44 UTC
    I didn't check if this snippet is in the links above....lazy Sunday...but it's worth mentioning.
    #!/usr/bin/perl use Proc::Queue size=>5, ':all'; my @script_names= qw(s1 s2 s3 s4 s5 somescript); my @pids; for my $s (@script_names) { push @pids, system_back($s) } %results=waitpids(@pids);

    I'm not really a human, but I play one on earth. flash japh