Optimal lock file method

后端 未结 6 1404
离开以前
离开以前 2020-11-30 23:25

Windows has an option to open a file with exclusive access rights. Unix doesn\'t.

In order to ensure exclusive access to some file or device, it is common practice

6条回答
  •  -上瘾入骨i
    2020-12-01 00:21

    Take a look at the enlightening presentation File Locking Tricks and Traps:

    This short talk presents several common pitfalls of file locking and a few useful tricks for using file locking more effectively.

    Edit: To address your questions more precisely:

    Is there a better synchronization method than the lock file?

    As @Hasturkun already mentioned and as the presentation above told, the system call you need to use is flock(2). If the resource you'd like to share across many users is already file-based (in your case it is /dev/ttyUSBx), then you can flock the device file itself.

    How to determine if the process who created the lock file is still running?

    You don't have to determine this, as the flock-ed lock will be automatically released upon closing the file descriptor associated with your file, even if the process was terminated.

    How making it possible for another user to remove the lock file if not in use?

    If you would lock the device file itself, then there will be no need to remove the file. Even if you would decide to lock an ordinary file in /var/lock, with flock you will not need to remove the file in order to release the lock.

提交回复
热议问题