Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Yes it does appear that you have a race condition in that code. Since what you are doing is very similar to the needs of a read/write operation I'd suggest using a second lock file (called a semaphore file) to lock the whole operation between testing the existance of PID_LOCK and finally writing $$ to the file. Eg.
sub single_instance{ $SIG{INT} = sub {exit()}; my ($prog) = $0 =~ m|(?:.*[/\\])?(.*)$|; my $tmp_dir = $^O =~ "MSWin32" ? "C:/Windows/Temp" : "/tmp"; my $lockfile = "$tmp_dir/$prog.pid"; local *PID_FILE; open(SLOCK,">$tmp_dir/$prog.slock") or die("single_instance(): Can +'t open slock: $!\n"); flock(SLOCK,2); if (-e $lockfile){ open(PID_FILE, "<$lockfile") or die("single_instance(): Can't +open $lockfile: $!\n"); my $running_pid = <PID_FILE>; close(PID_FILE); chomp($running_pid); if (kill 0, $running_pid){ die("Already running as pid $running_pid\n"); } } open(PID_FILE, "+>$lockfile") or die("single_instance(): Can't ope +n $lockfile: $!\n"); print PID_FILE "$$\n"; close(PID_FILE); close(SLOCK); chmod(0666, $lockfile); eval "END {unlink '$lockfile'}"; die("single_instance(): $@\n") if($@); }

This avoids the race condition because whichever process that first gets exclusive lock on the semephore file is able to read and write to the lock file before the other process can even test for the lock file's existance.

-caedes


In reply to Re: Determine if script is already running by caedes
in thread Determine if script is already running by Nitrox

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-23 18:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found