Nalina has asked for the wisdom of the Perl Monks concerning the following question:

Can anybody tell me how to lock a file for reading/writing and then release it and to check if the file is locked in perl on Unix?
Thanks in advance

Replies are listed 'Best First'.
Re: File locking
by Joost (Canon) on May 09, 2007 at 11:31 UTC
      But in my case I have some processes running in parallel and accessing the same file. Suppose Process1 is writing to a file, it should lock the file. and when procees2 has to write into the same file, it should check if the file is locked, if so wait till it is released and then write into it. How to implement this?
        If you lock a file for writing, it will automatically wait untill any other lock is released. In other words you can do this in both processes and it'll work:
        use Fcntl qw(:flock); # import LOCK_* constants open F,">>",$somefile or die $!; flock(F,LOCK_EX); # lock exclusively - waits for lock # write stuff here close(F); # close() will release the lock.
        A reply falls below the community's threshold of quality. You may see it by logging in.
Re: File locking
by mantra2006 (Hermit) on May 09, 2007 at 12:24 UTC
    Hey

    Just do a search for flock(). the following link has some interesting
    stuff.
    http://www.perlmonks.org/?node_id=178572

    Thanks & Regards
    Sridhar
Re: File locking
by mantra2006 (Hermit) on May 09, 2007 at 12:45 UTC
    To help resolve your 2nd question about 2 processes...here is the general thought...
    If 2 processes or more trying to access same file either you have to implement synchronization concept or threading concept means
    one process should complete then only you have to allow other to get access to a file...because both processes needs
    to access same file. find below some links which may shed you some idea on this...
    http://www.xav.com/perl/lib/Pod/perlthrtut.html http://www.globalspin.com/thebook/chapter20.html http://perldoc.perl.org/perlthrtut.html
    Thanks & Regards
    Sridhar
Re: File locking
by chrism01 (Friar) on May 09, 2007 at 23:43 UTC
    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
Re: File locking
by mantra2006 (Hermit) on May 15, 2007 at 12:59 UTC