0

I have developed a client application and server application which can both run on any Linux computer and communicate with each other.

I need to set some flag in each application to prevent a race condition when performing a particular operation on certain data. The operation involves reading and writing from files and deleting them afterwards.

Yes, I can set a flag in each application, for example bool in_use = true , then an API bool is_in_use() to get this value for example.

However, how can I ensure that the setting and reading of this flag will be atomic across all systems, hence only one application can read this flag or write it at the same time?

Engineer999
  • 3,683
  • 6
  • 33
  • 71
  • Are the client and server processes running on the same computer, where they can communicate via shared memory or some other local locking mechanism? – Peter Cordes Dec 02 '22 at 12:07
  • @PeterCordes No. That's the issue. Different machines – Engineer999 Dec 02 '22 at 12:10
  • 1
    Hmm, I wonder that even if you have a solution to the flag issue, the _reading and writing from files and deleting them_ still might not be safe. Perhaps that is the real question - how to sync file access? – chux - Reinstate Monica Dec 02 '22 at 12:31
  • A simple but imperfect solution would be to create a file myflag.txt that is empty or some junk data before proceeding, only if the file doesn't exist already, then delete it when you've finished. To do it properly though, I think you need to have a single server-like program that does the operation which you can call from either party so that it queues the requests. – Simon Goater Dec 02 '22 at 12:45
  • The Byzantine Generals told me they have not found a perfect solution. – stark Dec 02 '22 at 14:14

1 Answers1

1

You will have to localize the permission (one atomic flag in one place). Then have both (all) systems request the flag to start modifications, do whatever they need to and finally return the flag. Synchronizing multiple atomic flags over a network is borderline impossible. Either client or server can be in charge of the flag or a third distinct process.

  • When I think about it. Couldn't i use flock() to allow exclusive access to a file. Even if the file is empty, if one process has it already locked and another tries to get the lock it can't proceed. – Engineer999 Dec 02 '22 at 14:34
  • Can flock be used over a network? I'm not aware of any such functionality but if available yeah, it could be used as a flag. – Ignacio Gaviglio Dec 02 '22 at 15:16