From: Dietmar Maurer Date: Thu, 25 Apr 2013 09:35:35 +0000 (+0200) Subject: implement shared file locks X-Git-Url: https://git.proxmox.com/?p=pve-common.git;a=commitdiff_plain;h=493004a2b9571e598a4f11bbdf704354ac0003e1 implement shared file locks bump version to 3.0-5 --- diff --git a/data/PVE/Tools.pm b/data/PVE/Tools.pm index a55e427..235178a 100644 --- a/data/PVE/Tools.pm +++ b/data/PVE/Tools.pm @@ -19,6 +19,7 @@ use String::ShellQuote; our @EXPORT_OK = qw( lock_file +lock_file_full run_command file_set_contents file_get_contents @@ -79,22 +80,24 @@ sub run_with_timeout { my $lock_handles = {}; -sub lock_file { - my ($filename, $timeout, $code, @param) = @_; +sub lock_file_full { + my ($filename, $timeout, $shared, $code, @param) = @_; $timeout = 10 if !$timeout; + my $mode = $shared ? LOCK_SH : LOCK_EX; + my $lock_func = sub { if (!$lock_handles->{$$}->{$filename}) { $lock_handles->{$$}->{$filename} = new IO::File (">>$filename") || die "can't open file - $!\n"; } - if (!flock ($lock_handles->{$$}->{$filename}, LOCK_EX|LOCK_NB)) { + if (!flock ($lock_handles->{$$}->{$filename}, $mode|LOCK_NB)) { print STDERR "trying to aquire lock..."; my $success; while(1) { - $success = flock($lock_handles->{$$}->{$filename}, LOCK_EX); + $success = flock($lock_handles->{$$}->{$filename}, $mode); # try again on EINTR (see bug #273) if ($success || ($! != EINTR)) { last; @@ -135,6 +138,13 @@ sub lock_file { return $res; } + +sub lock_file { + my ($filename, $timeout, $code, @param) = @_; + + return lock_file_full($filename, $timeout, 0, $code, @param); +} + sub file_set_contents { my ($filename, $data, $perm) = @_;