How do I atomically create a locked file in Linux?

前端 未结 3 1513
误落风尘
误落风尘 2021-02-20 02:58

Scenario: I have many processes running that need to fetch files over the net. If the file is already downloaded, I want it cached on disk. If another process is downloading th

3条回答
  •  梦谈多话
    2021-02-20 03:16

    Why don't you use a lockfile utility?

    Examples

    Suppose you want to make sure that access to the file "important" is serialised, i.e., no more than one program or shell script should be allowed to access it. For simplicity's sake, let's suppose that it is a shell script. In this case you could solve it like this:

    ...
    lockfile important.lock
    ...
    access_"important"_to_your_hearts_content
    ...
    rm -f important.lock
    ...
    

提交回复
热议问题