2

Does the "open" function in Perl automatically checks whether a file is locked and wait for it to be unlocked? if so, how long does it wait or how can I control that period of time?

I have 5 forked processes appending data to the same file. Each forked process basically opens the file and then flocks it. It then appends its data and closes the file handler to unlock the file so that the other forked processes can use it.

Everything works as expected, but I'm afraid that the open command might timeout if one of the forked processes takes too long to complete its task.

JohnnyLoo
  • 877
  • 1
  • 11
  • 22
  • See [flock](http://perldoc.perl.org/functions/flock.html) for an example, including the note at the very end about `fork` calls – zdim Mar 20 '17 at 22:06

2 Answers2

9

flock only prevents locks from being obtained using flock; it doesn't prevent a file from being opened, read, modified or deleted.

flock without the LOCK_NB flag will block until a lock can be obtained, or until interrupted by a signal.

flock with the LOCK_NB flag will return immediately.

  • If flock was able to obtain a lock, it will return true.
  • If flock was unable to obtain a lock, it will return false, and errno will be set.
    • $!{EINTR} indicates that operation was interrupted by a signal.
    • $!{EWOULDBLOCK} indicates that waiting would be required but LOCK_NB was specified.
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • I see. How can I make a forked process check if there is a lock on a file and then wait until the file is unlock so that it writes its data into the file? – JohnnyLoo Mar 21 '17 at 13:11
  • Nevermind, you just answered my question. I just have a doubt now, how long would flock wait before it gives up waiting for a file to be unlocked? – JohnnyLoo Mar 21 '17 at 13:21
  • I've clearly specified under which conditions `flock` returns in my answer. Without `LOCK_NB`, it will wait until interrupted by a signal. – ikegami Mar 21 '17 at 15:37
2

No, open does not interact with locks at all. Locking a file just prevents others from locking it, nothing else.

melpomene
  • 84,125
  • 8
  • 85
  • 148