icon Top 9 categories map      RocketAware > Perl >

What can't I just open(FH, ">file.lock")?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

What can't I just open(FH, ">file.lock")?

A common bit of code NOT TO USE is this:

    sleep(3) while -e "file.lock";      # PLEASE DO NOT USE
    open(LCK, "> file.lock");           # THIS BROKEN CODE

This is a classic race condition: you take two steps to do something which must be done in one. That's why computer hardware provides an atomic test-and-set instruction. In theory, this ``ought'' to work:

    sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT, 0644)
                or die "can't open  file.lock: $!":

except that lamentably, file creation (and deletion) is not atomic over NFS, so this won't work (at least, not every time) over the net. Various schemes involving involving link() have been suggested, but these tend to involve busy-wait, which is also subdesirable.


Source: Perl FAQ: Files and Formats
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: I still don't get locking. I just want to increment the number in the file. How can I do this?

Previous: How can I lock a file?



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: File Access Limits




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq5/What_can_t_I_just_open_FH_fil.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments