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.
#!/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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER