Detecting a program is running.

D

Dave

Hi,

How can I use perl to detect a program is running?
This is typically used when program A running, A do not want to running
multiple copies of itself.

Thanks
Sam
 
P

phaylon

Dave said:
How can I use perl to detect a program is running? This is typically used
when program A running, A do not want to running multiple copies of
itself.

How about a system-wide lock- and pid-file? The latter to find out if the
process is still running. Another -but not that save- approach might be to
work with $0 and the process table, but I think I would prefer the first.
I use the second method mostly only for short scripts on my own servers
so those can tell me «Another one's still running, I'm waiting.»

hth a bit,p
 
C

Charles DeRykus

Hi,

How can I use perl to detect a program is running?
This is typically used when program A running, A do not want to running
multiple copies of itself.

Maybe something like this:

#|------- ensure only 1 instance is running
use Fcntl qw:)flock);
BEGIN { open FH, '>', 'mylock' and flock FH, LOCK_EX|LOCK_NB
or die "already running: $!\n";
}


hth,
 
J

Joe Smith

Dave said:
How can I use perl to detect a program is running?
This is typically used when program A running, A do not want to running
multiple copies of itself.

If your platform is Linux:

linux% cat /usr/local/bin/run-unique
#!/usr/bin/perl
# Purpose: Starts a command only if it is not already running

use strict; use warnings;

my $Usage = "Usage: $0 command args\n Runs command if not already
running\n";
my @cmd = @ARGV or die $Usage;
my $cmd_line = "@cmd";
die "Command line too long: $cmd_line\n" if length $cmd_line > 4095;

my ($user,$header) = get_uid_from_ps();
my $count = 0;
foreach (`ps -efww`) { # This has a limit of 4096 bytes for CMD
my ($who,$pid,$cmd) = (split /\s+/,$_,7)[0,1,6];
next unless $who eq $user and $cmd =~ /\Q$cmd_line\E$/;
next if $pid == $$;
print STDERR " $user is running '$cmd_line'\n$header" unless $count++;
print STDERR $_;
}
print STDERR " count = $count\n" if $count > 1;
exit 1 if $count;
print "$cmd_line\n";
exec @cmd;

sub get_uid_from_ps {
my @ps = `ps -fp $$`;
my @cols = split ' ',$ps[0];
$_ = "UID PID PPID C STIME TTY TIME CMD";
die "'@cols' != '$_'" unless "@cols" eq $_;
@cols = split ' ',$ps[1];
($cols[0], $ps[0]);
}
 
A

andrewflanders

If you are using unix I would wrap the perl program in a bash script
that saves the contents of the "ps ax" command to a tmp directory so
that when it first runs it greps the tmp file for an occurence of
itself and exits if it finds any matches.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top