in reply to opening files: link checking and race conditions

correction: this reply, though maybe not totally stupid on its own, is irrelevant to the OP (thanks to dave_the_m for waking me up.)

I adapted some code from an old Perl Journal article by Sean Burke, and I've been using it for years; I posted it here a while back, in response to a similar SoPW thread.

The basic idea is called a "semaphore" file -- a separate file from the one you intend to modify, whose sole purpose is to be the object of an flock operation. Since you aren't going to modify the semaphore file in any way, you side-step the race condition issue. Once one process owns the semaphore, it can do what ever number of steps it needs to in an "atomic" fashion, then free the semaphore for some other process.

Hope that helps.

(update: I just noticed that the url embedded in my posted "Semfile.pm" code is no longer usable -- 404. TPJ is still available online, and you can get the article reference by searching for "semaphore file Sean Burke", but you have to pay for a subscription to TPJ to see it. Bear in mind that the TPJ subscription is definitely a good investment. Apologies for the broken link.)

  • Comment on Re: opening files: link checking and race conditions

Replies are listed 'Best First'.
Re^2: opening files: link checking and race conditions
by dave_the_m (Monsignor) on Aug 03, 2005 at 02:03 UTC
    That's only useful for cooperating processes. The OP is talking about a malicious attempt to exploit a race condition.

    The only thing I can think of is to use O_NOFOLLOW, which isn't portable (but should work on Linux and BSD systems):

    use Fcntl; sysopen F, "/tmp/foo", O_RDONLY|O_NOFOLLOW;

    Dave.