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; }
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |