C++ Code Snippet – File Locking

I program applications that run on IBM AIX servers at work. Multiple people will be running different instances of my programs, and if any of my programs are writing to a file at any time, it could become problematic. For example:

  1. Person 1 runs MyProg, which opens MyFile.txt, which contains the text “Hello, World.”
  2. Person 2 runs MyProg, and also opens MyFile.txt, which contains the text “Hello, World.”
  3. Person 1 now makes edits to MyFile.txt and saves it, so now it reads “Hello, World. Beautiful day today!” He exits the program.
  4. Person 2 then makes his edits to MyFile.txt, which reads “Hello, World. Person 1 is a jerk!” and saves.
  5. Person 1 gets fired.

Because there’s no locking, data can get overwritten without anyone noticing.


6. Person 1 goes outside and finds (what's left of) his bike

Continue reading C++ Code Snippet – File Locking