atomic create file if not exists from bash script

前端 未结 6 1653
盖世英雄少女心
盖世英雄少女心 2020-12-15 22:24

In system call open(), if I open with O_CREAT | O_EXCL, the system call ensures that the file will only be created if it does not exist. The atomic

6条回答
  •  猫巷女王i
    2020-12-15 22:36

    Just to be clear, ensuring the file will only be created if it doesn't exist is not the same thing as atomicity. The operation is atomic if and only if, when two or more separate threads attempt to do the same thing at the same time, exactly one will succeed and all others will fail.

    The best way I know of to create a file atomically in a shell script follows this pattern (and it's not perfect):

    1. create a file that has an extremely high chance of not existing (using a decent random number selection or something in the file name), and place some unique content in it (something that no other thread would have - again, a random number or something)
    2. verify that the file exists and contains the contents you expect it to
    3. create a hard link from that file to the desired file
    4. verify that the desired file contains the expected contents

    In particular, touch is not atomic, since it will create the file if it's not there, or simply update the timestamp. You might be able to play games with different timestamps, but reading and parsing a timestamp to see if you "won" the race is harder than the above. mkdir can be atomic, but you would have to check the return code, because otherwise, you can only tell that "yes, the directory was created, but I don't know which thread won". If you're on a file system that doesn't support hard links, you might have to settle for a less ideal solution.

提交回复
热议问题