What follows is Linux/Solaris-centric. Proc::ProcessTable probably works on other platforms, but there's a good chance that the process table field names will be different.

If your machine is busy, and renicing your code with setpriority(0, $$, NEW_PRIORITY) (where NEW_PRIORITY is a small natural number) won't help 'cos there are too many copies of your program running, consider using the following code. The example limits the number of instances to 5, and will die if you try to start more.

sub limit_instance($$); # proto use constant MAX_INST => 5; my $clones = limit_instance( $0, MAX_INST ); print 'There is/are ', $clones, ' of me running.', "\n"; sleep 60; # in real life, you would do something here exit; sub limit_instance($$) { # takes two args: # 1: command line name of program to limit ($0 is the current Perl + file) # 2: maximum number of instances use Proc::ProcessTable; use integer; my ( $program, $limit ) = @_; return undef unless ( defined($program) && defined($limit) ); my $p = new Proc::ProcessTable; my $count = 0; foreach my $process ( @{ $p->table } ) { $count++ if ( $process->{'cmndline'} =~ m/$program/ ); die "Limit of $limit instances passed.\n" if ( $count > $limit + ); } return $count; }

In reply to limiting number of program instances with Proc::ProcessTable by Willard B. Trophy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.