File locking for all my needs

M

Matija Papec

I thought this could be usefull to someone but before you use it bear in
mind its limitations,

- probably works as expected only on Linux and other *nix like systems
- only convenient for text files
- handling very large files is not efficient
- if it isn't there, file gets created (this is a feature actually)
- ?

Function can be used in two ways, I generally use second for log files and
first for all other purposes..


#1) managing whole file at once
my @txt;
my $fh = OpenLock('/tmp/testing.txt', \@txt);
print $fh "top line\n", @txt;
close $fh;

#2) append lines to file
my $fh = OpenLock('/tmp/testing.txt');
print $fh "bottom line\n";
close $fh;


sub OpenLock {
###############################################################
#
# open rw, flock, fill @$ra, truncate file to zero, return FH
#
###############################################################

my($file, $ra) = @_;
local *FH;

open FH, "+>>$file" or die $!;
flock(FH, 2); #exclusive_lock
if ($ra) {
seek(FH, 0, 0);
@$ra = <FH>;
seek(FH, 0, 0);
truncate(FH, 0);
}
return(*FH);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top