A PID-based approach to process exclusion suffers from the possibility of PID re-use. Also, there is usually no atomic way of checking the pid *and* registering it. That doesn't mean the approach can't be used in practice, but there is a small probability of malfunction.

A safe approach can be based on file locking (flock), which is *meant* to guarantee exclusive access. The following code shows how that can be done in a Unix-ish environment. I'm sure there is already a module on CPAN (or two) that does this in a more portable way, but I couldn't find it in a hurry.

#!/usr/local/bin/perl use strict; use warnings; $| = 1; use Fcntl qw( :flock); my $name = 'ttt'; # process name my $pid_file = "/var/run/$name.pid"; open my $pid_handle, '+<', $pid_file or die "Can't access '$pid_file': + $!"; flock $pid_handle, LOCK_EX | LOCK_NB or die "Process $name is still ac +tive"; truncate $pid_handle, 0 or die "Truncating '$pid_file' failed: $!"; print $pid_handle "$$\n"; # Normal processing starts here # # ... sleep 10; # for testing
Update: I forgot to mention that the file /var/run/ttt.pid must be pre-created and given ownership and permissions so that the user that runs the process can write it.

Anno


In reply to Re: Process Already Running by Anno
in thread Process Already Running by Photius

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.