How do I lock a file in Perl?

前端 未结 14 597
礼貌的吻别
礼貌的吻别 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 05:54

    Ryan P wrote:

    In this case the file is actually unlocked for a short period of time while the file is reopened.

    So don’t do that. Instead, open the file for read/write:

    open my $fh, '+<', 'test.dat'
        or die "Couldn’t open test.dat: $!\n";
    

    When you are ready to write the counter, just seek back to the start of the file. Note that if you do that, you should truncate just before close, so that the file isn’t left with trailing garbage if its new contents are shorter than its previous ones. (Usually, the current position in the file is at its end, so you can just write truncate $fh, tell $fh.)

    Also, note that I used three-argument open and a lexical file handle, and I also checked the success of the operation. Please avoid global file handles (global variables are bad, mmkay?) and magic two-argument open (which has been a source of many a(n exploitable) bug in Perl code), and always test whether your opens succeed.

提交回复
热议问题