Optimal lock file method

后端 未结 6 1408
离开以前
离开以前 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条回答
  •  眼角桃花
    2020-12-01 00:21

    To expand on Hasturhun's answer. Instead of using the presence or absence of the lock file as an indicator, you need to both create the lock file if it dosen't exists and then get an exclusive lock on the file.

    The advantages of this approach is that unlike many other methods of syncing programs, the OS should tidy up for you if your program exits without unlocking.

    So the program structure would be something like:

    1: open the lock file creating it if it doesn't exist
    2: ask for an exclusive lock an agreed byte range in the lock file
    3: when the lock is granted then
        4: 
        5: release my lock
        6: close the lock file
    end
    

    At step: you can either block waiting for the lock to be granted or return immediately. The bytes you lock don't actually have to exist in the file. If you can get hold of a copy of Advanced Unix Programming by Marc J. Rochkind, he develops a complete C library that uses this method to provide a way of syncing programs that gets tidied up by the OS, however the programs exit.

提交回复
热议问题