toniax has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
I am having trouble tuning some code in my script.
I figured out one way to do it. I will show below
I would rather just change the code instead of using flock but I can not figure
out a way to do it.
use Fcntl qw(:flock); my $file = '/home/X/public_html/filelock'; my $SEMAPHORE = "$file.lck"; open(LOCK, ">$SEMAPHORE") || die $!; flock(LOCK, LOCK_EX); unless (-e "file.html") { open (HTMLFILE,">file.html"); require 'html_head_page.pl'; close (HTMLFILE); close(LOCK); unlink("$SEMAPHORE"); }

Replies are listed 'Best First'.
Re: Race conditions
by ikegami (Patriarch) on Nov 16, 2010 at 18:48 UTC

    To achieve the same effect without locking, you can write the HTML to a temp file, then rename the file to the final name.

      Hi,
      I was not at all clear with my post . I thought I could use flock on -unless-
      to prevent a race condition. since the code is in between the opening and closing of the
      semaphore file. I can not figure out a different way to check if a file exist and write to it ,so it is not possible
      for a race condition to accrue as it could using unless.

        Actually, this is the post that I can't understand. What do you want your code to do?

Re: Race conditions
by anonymized user 468275 (Curate) on Nov 16, 2010 at 16:08 UTC
    What alternative functionality to flock are you looking for? I do wonder about the use of "unless" together with flock -- this means that, potentially, losing the race has more than one possible consequence (wait for lock or abort) depending on where in the thread a race is lost. Is that intended?

    One world, one people

      While the OPs code makes little sense, your comment isn't all that clear either. There's no losing the race with flock. The flock is blocking. If someone else gets the lock first, the current process will politely wait till the other is done, and then it gets turn, while no other process using the semaphore will interfere.

      Now, I've big questions about any of the OPs code that isn't involved in the locking - but I don't see a problem with the locking in itself.

      Yes, that was my intention.
Re: Race conditions
by happy.barney (Friar) on Nov 16, 2010 at 17:27 UTC
    do you want to have only one process that creates "file.html" ?
    Then use IO::File with O_CREAT | O_EXCL and you can remove flock.
    Or is there something hidden ?

    Btw, it looks to me that proper unlink argument should be $SEMAPHORE.