fcntl, lockf, which is better to use for file locking?

后端 未结 5 1411
春和景丽
春和景丽 2020-11-28 21:32

Looking for information regarding the advantages and disadvantages of both fcntl and lockf

5条回答
  •  情书的邮戳
    2020-11-28 21:47

    Your main concerns, in this case (i.e. when "coding a Linux daemon and wondering which is better suited to use for enforcing mutual exclusion"), should be:

    1. will the locked file be local or can it be on NFS?
      • e.g. can the user trick you into creating and locking your daemon's pid file on NFS?
    2. how will the lock behave when forking, or when the daemon process is terminated with extreme prejudice e.g. kill -9?

    The flock and fcntl commands behave differently in both cases.

    My recommendation would be to use fcntl. You may refer to the File locking article on Wikipedia for an in-depth discussion of the problems involved with both solutions:

    Both flock and fcntl have quirks which occasionally puzzle programmers from other operating systems. Whether flock locks work on network filesystems, such as NFS, is implementation dependent. On BSD systems flock calls are successful no-ops. On Linux prior to 2.6.12 flock calls on NFS files would only act locally. Kernel 2.6.12 and above implement flock calls on NFS files using POSIX byte range locks. These locks will be visible to other NFS clients that implement fcntl()/POSIX locks.1 Lock upgrades and downgrades release the old lock before applying the new lock. If an application downgrades an exclusive lock to a shared lock while another application is blocked waiting for an exclusive lock, the latter application will get the exclusive lock and the first application will be locked out. All fcntl locks associated with a file for a given process are removed when any file descriptor for that file is closed by that process, even if a lock was never requested for that file descriptor. Also, fcntl locks are not inherited by a child process. The fcntl close semantics are particularly troublesome for applications which call subroutine libraries that may access files.

提交回复
热议问题