[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 749
  • Last Modified:

Check whether a file is locked or not

Hi
In perl I can lock a file using flock(). But is there any way of knowing whether a file to be opened is already locked using flock() or not.
Regards
Nitin
0
nitindn
Asked:
nitindn
1 Solution
 
prady_21Commented:
this is what i used in a pgm from perl cook book, hope it helps, it is straight of the book

unless(flock(FH, LOCK_EX|LOCK_NB)) {
 warn "cant immediately write-lock the file , blocking..";
 unless (flock(FH, LOCK_EX)) {
    die "cant get write lock on file:$!";
  }
}

If LOCK_NBis used and LOCK_SH is refused, then some one has a LOCK_EX on the file, if LOCK_EX is refused then some one else holds LOCK_SH or LOCK_EX, so do not update the file.
0
 
ItatsumakiCommented:
Yup, if you can't flock(2) a file, then someone else has it locked.

if (!flock(OUT, 2)) {
  die "Can't lock file!\n";
  }
0
 
nitindnAuthor Commented:
Hi,
What you all say is fine, but in my case I have two perl scripts running simultaneously. Both are trying to write to a file.
My need is that if one of the scripts find out that the file has been locked by the other one, then it should exit. But what is happening is that the second script wais for the first script to release the lock and then it proceeds.
The code for the script is something like this:
Script 1:
open( _MCpidfile_ , ">C:\\TestThreadsforMC\\abc.dat" );
flock(_MCpidfile_, 2 ) or die "cannot lock file: C:\\TestThreadsforMC\\abc.dat ";
for ($count = 1 ;$count < 51; $count++ )
{
     print _MCpidfile_ "\n$count" ;
}
close (_MCpidfile_) ;

Script 2:
open( _MCpidfile_ , ">>C:\\TestThreadsforMC\\abc.dat" );
if (! flock ( _MCpidfile_ , 2))
{
     print "\ncan't lock file" ;
        exit(1);
}
print _MCpidfile_ "\nhi..just testing" ;
close (_MCpidfile_);

Now can you suggest what i should do..?
Regards
Nitin
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
ozoCommented:
use LOCK_NB as prady_21 said
flock(_MCpidfile_, 2|4) or die "cannot lock file: C:\\TestThreadsforMC\\abc.dat ";
0
 
nitindnAuthor Commented:
Hi,
Can you tell me what does this LOCK_NB do and hat it means..
Regards
Nitin
0
 
ozoCommented:
see
perldoc -f flock
If LOCK_NB is bitwise-or'ed with LOCK_SH or
LOCK_EX then `flock' will return immediately
rather than blocking waiting for the lock (check
the return status to see if you got it).
0
 
nitindnAuthor Commented:
Hi,
Can you tell me what does this LOCK_NB do and hat it means..
Regards
Nitin
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now