doctormelodious
doctormelodious

Reputation: 41

In Perl script, I can open / write to/ and close a file, but I get "bad file descriptor" when I try to flock it

I can OPEN the file using the file handle, but when I try to FLOCK using the same file handle I get "bad file descriptor."

my $file='/Library/WebServer/Documents/myFile.txt';
open(my $fh, '>', $file) or die "Could not open '$file' - $!";
    # I DO NOT GET AN ERROR FROM OPENING THE FILE

flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";
    # HERE IS WHERE I GET THE "BAD FILE DESCRIPTOR" ERROR
    # IF I COMMENT THIS LINE OUT, THE PRINT AND CLOSE COMMANDS BELOW EXECUTE NORMALLY

print $fh "hello world";
close($fh) or die "Could not write '$file' - $!";

It's the same file handle, so why do OPEN and PRINT work, but not FLOCK? I have tried setting the permissions for the file to 646, 666, and 777, but I always get the same results.

Thanks!

Upvotes: 0

Views: 599

Answers (1)

mob
mob

Reputation: 118605

Did you import the constant LOCK_EX per the flock documentation?

use Fcntl ':flock';

If not, LOCK_EX doesn't mean anything and the flock call will fail. Using strict and/or warnings would have identified a problem with this system call.

Upvotes: 2

Related Questions