SPUG: Perl Question?

dleonard at dleonard.net dleonard at dleonard.net
Wed May 4 15:01:56 PDT 2005


On Wed, 4 May 2005, James Moore wrote:

> > I would recommend instead querying the process table for other processes
> > running as $0.
>
> There's no atomic way of doing this that I know about, though.  You need
> some sort of real mutex mechanism; lock files, semaphores, whatever, but
> something that helps you deal with race conditions.
>
> I guess you could do something like look at the process table and declare
> that the lowest PID wins; if there's another process running and its PID <
> your PID, then you should exit.  Feels suspicious, though - am I missing
> something that would break this?  For one, it's not portable, but I'd also
> assume in my suspicious little heart that anything relying on file locking
> is going to snap like a twig if you try to go between substantially
> different OSes, too.

Sequential process ids aren't a guarantee nowadays.  However, if all you are trying to do is guarantee singleton or fixed number of running processes then querying proc via Proc::ProcessTable or a home grown solution (what I've commonly done) pretty much eliminates the possible of multiple processes of the same time running simultaneously.

On a unix box something as simple as

my @procs = `ps axo command | grep $0 | grep -v grep`;
die "More than one [$0] process running.\n" if scalar @procs > 1;

is good enough in most instances.  It doesn't handle substrings or other processes that operate on the thing you are executing but instead errs on the side of caution.

--

DL



More information about the spug-list mailing list