How do I lock a file in Perl?

前端 未结 14 584
礼貌的吻别
礼貌的吻别 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:56

    Here's my solution to reading and writing in one lock...

    open (TST,"+< readwrite_test.txt") or die "Cannot open file\n$!";
    flock(TST, LOCK_EX);
    # Read the file:
    @LINES=;
    # Wipe the file:
    seek(TST, 0, 0); truncate(TST, 0);
    # Do something with the contents here:
    push @LINES,"grappig, he!\n";
    $LINES[3]="Gekke henkie!\n";
    # Write the file:
    foreach $l (@LINES)
    {
       print TST $l;
    }
    close(TST) or die "Cannot close file\n$!";
    

提交回复
热议问题