/
usr
/
local
/
lp
/
apps
/
malre
/
scripts
/
File Upload :
llllll
Current File: //usr/local/lp/apps/malre/scripts/lock_file.pm
use strict; use warnings; use Fcntl ':flock'; ### Requires there to be a $main::d_working holding the working directory my $fh_locked1; my $b_leave_open = 0; sub fn_lock_file { ### $_[0] is the full path to the file ### $_[1] "1": get a lock or die, "2": wait for a lock, "3": close the file ("2" is assumed) ### $_[2] if $_[1] is "3", this can be a file handle that needs to be closed ### Capture the arguments that were passed my ( $f_lock, $v_type, $v_fh ) = @_; ### If the file handle wasn't captured from the previous lock, unlock it if ( $v_type != 3 || ( defined $v_fh && defined $fh_locked1 && $v_fh ne $fh_locked1 ) ) { if ( defined $fh_locked1 && ! $b_leave_open ) { close( $fh_locked1 ); } undef $fh_locked1; } elsif ( $v_type == 3 && ! defined $v_fh ) { $v_fh = $fh_locked1; } $b_leave_open = 0; ### If the file doesn't exist MAKE it exist if ( defined $f_lock && ! -f $f_lock && open( my $fh_append, '>>', $f_lock ) ) { close( $fh_append ); } if ( ( ! defined $v_type || $v_type =~ m/^[12]$/ ) && open( $fh_locked1, '+<', $f_lock ) ) { ### If desired, get a lock on the file if ( defined $v_type && $v_type == 1 ) { flock( $fh_locked1, LOCK_EX | LOCK_NB ) || return 0; } elsif ( ! defined $v_type || $v_type == 2 ) { flock( $fh_locked1, LOCK_EX ); } return 1; ### If we're closing out a file... } elsif ( $v_type == 3 ) { my $b_success = 0; ### Close out the appropriate file if ( defined $v_fh && close( $v_fh ) ) { $b_success = 1; } elsif ( defined $fh_locked1 && close( $fh_locked1 ) ) { $b_success = 1; undef $fh_locked1; } return $b_success; } return 0; } sub fn_get_fh { ### This will pass you the file handle and prevent it from being closed $b_leave_open = 1; return $fh_locked1; } #========================# #== Shortcut Functions ==# #========================# ### For these pairs, when you do the open part, it remembers the files that you're working with so that you can later do the close part my %fh_locked2; sub fn_get_lock { ### $_[0] is the name of the file that we want to lock my $f_locked = $_[0]; my $v_return = fn_lock_file( $f_locked, 2, undef ); if ( $v_return ) { $fh_locked2{$f_locked} = fn_get_fh(); return $fh_locked2{$f_locked}; } return 0; } sub fn_release_lock { ### $_[0] is the name of the file that we want to unlock my $f_locked = $_[0]; my $v_return = fn_lock_file( $f_locked, 3, $fh_locked2{$f_locked}); delete $fh_locked2{$f_locked}; return $v_return; } 1;
Copyright ©2k19 -
Hexid
|
Tex7ure