Link to home
Start Free TrialLog in
Avatar of bemara57
bemara57

asked on

flock() not working in my Perl script.. Why??

I'm trying to test if a file is opened by another process but am not getting any results for the flock command in Perl. I have a very simple test script:

#!/usr/bin/perl
use Fcntl qw(:DEFAULT :flock);
use strict;
open(FH, "<test.txt");
print flock(FH,LOCK_EX|LOCK_NB);
close(FH);

No mater if the file is opened or not, it returns 0 all the time, which means that it is locked. What am I doing wrong? It is running on Unix AIX. Is there a system command I should use or is flock pretty accurate at the OS level? I'm asking because not only my script is accessing this file, but a completely different software program is access the file. So I want to be able to detect is the file is open at all but I'm not getting any results. Please help! Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bemara57
bemara57

ASKER

So if another process is using the file but doesn't use any flock, how can I determine if the file is used by that other process? Any alternatives to flock? All i want to do is detect if the file is in use so I can modify it, otherwise I want it stuck in a loop until it is freed up (maybe 10 minute loop-kill).
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
using lsof can suffer from a race condition if another process opens a file in between the time you do the lsof and the time you modify the file.
If  the other process won't cooperate in using locking mechanism, and it is only doing reads,
and you are the only one doing writes, you might be able to do something like make a copy of the file, do your modifications on the copy, then rename the copy to the original.
Then any other process that opens the file will either get the original or the modification, and not some intermediate state.