As joost said originally, it's all explained with example in the official docs he linked to.
You don't need to learn about threading.
Having said that, I always implement the file open/local/write (or read)/unlock/close sequence in one sub.
The correct sequence is as per prev sentence. Don't worry about having the file open in multiple instances.
One note re the Perl docs though, lock is now a keyword (used in threaded programs). Prob best not to use it as a sub name to avoid confusion.
Here's one I wrote :
#*********************************************************************
+*********
#
# Function : log_msg
#
# Description : Log a msg in shared log file ie 1 file for all serve
+r
# instances.
#
# Params : $_[0] log msg
#
# Returns : none
#
#*********************************************************************
+*********
sub log_msg
{
my (
$log_msg, # msg to be logged
$datestamp, # Timestamp in format: Tue Oct 26 12:07:54 2004
$logfile, # final logfile name
$filename, # filename sans extension
$filext, # filename extension
$filedir, # current dir
$error_msg # error if any
);
# Assign input params
$log_msg = $_[0];
# Get Timestamp in format: Tue Oct 26 12:07:54 2004
$datestamp = localtime;
# Get filename components
($filename, $filedir, $filext) = fileparse($0, '\..*');
# Create filename, open with Exclusive lock
$logfile = "${cfg::params{'LOG_DIR'}}/${filename}${filext}.log";
open(CLIENT_LOG, ">>$logfile") or
$error_msg = "log_msg(): Can't open $logfile: $!";
if( !$error_msg )
{
flock(CLIENT_LOG, LOCK_EX) or
$error_msg = "log_msg(): Can't lock $logfile: $!";
}
# If ok, log msg contents
if( !$error_msg )
{
print CLIENT_LOG "$datestamp : $$ : $log_msg\n";
# Release lock & close
flock(CLIENT_LOG, LOCK_UN) or
$error_msg = "log_msg(): Can't unlock $logfile: $!";
close(CLIENT_LOG) or
$error_msg = "log_msg(): Can't close $logfile: $!";
}
# Log & email admin if an error occurred
if( $error_msg )
{
print "$error_msg\n"; # desperation / belt & braces
send_email($error_msg);
}
}
Cheers
Chris
|