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; }