icon Top 9 categories map      RocketAware > Perl >

I still don't get locking. I just want to increment the number in the file. How can I do this?

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, ...

    

I still don't get locking. I just want to increment the number in the file. How can I do this?

Didn't anyone ever tell you web-page hit counters were useless?

Anyway, this is what to do:

    use Fcntl;
    sysopen(FH, "numfile", O_RDWR|O_CREAT, 0644) or die "can't open numfile: $!";
    flock(FH, 2)                                 or die "can't flock numfile: $!";
    $num = <FH> || 0;
    seek(FH, 0, 0)                               or die "can't rewind numfile: $!";
    truncate(FH, 0)                              or die "can't truncate numfile: $!";
    (print FH $num+1, "\n")                      or die "can't write numfile: $!";
    # DO NOT UNLOCK THIS UNTIL YOU CLOSE
    close FH                                     or die "can't close numfile: $!";

Here's a much better web-page hit counter:

    $hits = int( (time() - 850_000_000) / rand(1_000) );

If the count doesn't impress your friends, then the code might. :-)


Source: Perl FAQ: Files and Formats
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How do I randomly update a binary file?

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



(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/I_still_don_t_get_locking_I_jus.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments