Search code examples
c++lockingdirectoryblock

Stop two instances of my application writing to the same folder simultaneously


I have an application that writes files to a folder, I want to prevent (or at least show a warning) if another instance of my application attempts to write to the same directory.

Is there a way I can temporarily block access to a folder to prevent this from happening?

EDIT:

I had an idea about creating a temp file to use as a flag, however is there a way to ensure that a temp file is deleted if my application were to crash?


Solution

  • Why not use a lock file?

    You have to ensure, that the "check-and-create" operation is atomic. If it tells You that the lockfile already exists, then there is another process accessing the directory.

    Blocking the whole directory for other processes is not what You want. You would also block shells and files browsers from accessing it.


    I saw Your edit: You could write the process ID of the file into the lockfile. If Your application detects an existing lock file, it can check if a process with that ID exists. If it doesn't, remove the lockfile and start over.