A common locking method is to create a second file in the same place as the main file. The second file may contain lock data or be empty. The advantage of having lock data (such as a process identifier) ββis that you can easily spot an outdated lock file, which inevitably needs to be planned. Although the PID may not be the best amount of lock data in your case.
Example: Service1:
- creates
myfile.lock - creates / opens
myfile
Service2:
- Notes that
myfile.lock present and pauses / blocks / waits - When
myfile.lock leaves, it creates it and then opens myfile.
It would also be useful to verify that the file contains your information about the lock (identification specific to your service) immediately after its creation - just in case you wait for two or more services and create a lock at the same time. The latter succeeds, and therefore all other services should notice that their lock data is no longer in the file. Also - pause a few milliseconds before checking its contents.
source share