Search code examples
perlflock

Perl Open and Flock timeout


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.


Solution

  • 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.