unixforkatomiclseek

if parent and child processes append to same file, do lseek() and write() need to be atomic?


Problem Statement

One process opens a file for appending (assume there is no O_APPEND, appending here means first lseek() to the file end then write()), and then forks a child. The two dependent processes append to the file simultaneously. Assume that lseek() and write() are both atomic. Give an example to discuss the necessity of having lseek() and write() be an atomic operation in this scenario.

My Thoughts

  1. The current file offset is stored in the entry in open file table, and that entry is shared by the 2 dependent processes.
  2. write() updates the offset to the end of the data just written.

These 2 points guarantee that even in the following scenario, the data written by P2 won't be overwritten by P1.

P1 lseek()
P2 lseek()
P2 write()  // after this operation, the offset still points to the file end
P1 write()

My Problem

So, do lseek() and write() still need to be one atomic operation in this specific case?


Solution

  • It turned out it's the wording making me question myself.

    The answer is that they don't have to be an atomic operation in this specific case.