atomic create file if not exists from bash script

前端 未结 6 1652
盖世英雄少女心
盖世英雄少女心 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条回答
  •  感动是毒
    2020-12-15 22:54

    Another way to do this is to use umask to try to create the file and open it for writing, without creating it with write permissions, like this:

    LOCK_FILE=only_one_at_a_time_please
    UMASK=$(umask)
    umask 777
    echo "$$" > "$LOCK_FILE"
    umask "$UMASK"
    trap "rm '$LOCK_FILE'" EXIT
    

    If the file is missing, the script will succeed at creating and opening it for writing, despite the file being created without writing permissions. If it already exists, the script won't be able to open the file for writing. It would be possible to use exec to open the file and keep the file descriptor around.

    rm requires you to have write permissions to the directory itself, without regards to file permissions.

提交回复
热议问题