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