atomic create file if not exists from bash script

前端 未结 6 1651
盖世英雄少女心
盖世英雄少女心 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:45

    You could create it under a randomly-generated name, then rename (mv -n random desired) it into place with the desired name. The rename will fail if the file already exists.

    Like this:

    #!/bin/bash
    
    touch randomFileName
    mv -n randomFileName lockFile
    
    if [ -e randomFileName ] ; then
        echo "Failed to acquired lock"
    else
        echo "Acquired lock"
    fi
    

提交回复
热议问题