How do I lock a file in Perl?

前端 未结 14 538
礼貌的吻别
礼貌的吻别 2020-12-01 05:45

What is the best way to create a lock on a file in Perl?

Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock

相关标签:
14条回答
  • 2020-12-01 06:16

    My goal in this question was to lock a file being used as a data store for several scripts. In the end I used similar code to the following (from Chris):

    open (FILE, '>>', test.dat') ; # open the file 
    flock FILE, 2; # try to lock the file 
    # do something with the file here 
    close(FILE); # close the file
    

    In his example I removed the flock FILE, 8 as the close(FILE) performs this action as well. The real problem was when the script starts it has to hold the current counter, and when it ends it has to update the counter. This is where Perl has a problem, to read the file you:

     open (FILE, '<', test.dat');
     flock FILE, 2;
    

    Now I want to write out the results and since i want to overwrite the file I need to reopen and truncate which results in the following:

     open (FILE, '>', test.dat'); #single arrow truncates double appends
     flock FILE, 2;
    

    In this case the file is actually unlocked for a short period of time while the file is reopened. This demonstrates the case for the external lock file. If you are going to be changing contexts of the file, use a lock file. The modified code:

    open (LOCK_FILE, '<', test.dat.lock') or die "Could not obtain lock";
    flock LOCK_FILE, 2;
    open (FILE, '<', test.dat') or die "Could not open file";
    # read file
    # ...
    open (FILE, '>', test.dat') or die "Could not reopen file";
    #write file
    close (FILE);
    close (LOCK_FILE);
    
    0 讨论(0)
  • 2020-12-01 06:16

    flock creates Unix-style file locks, and is available on most OS's Perl runs on. However flock's locks are advisory only.

    edit: emphasized that flock is portable

    0 讨论(0)
提交回复
热议问题