1

I am making a logging API where I use fprintf to print to a log file. Since fprintf is an atomic operation, the log messages won't overwrite each other even if multiple threads of a same process writes to the same file simultaneously.

I am not sure I fully understand the concept of atomic operation in context of multiprocessing. What will happen if multiple processes start writing to the same file simultaneously using fprintf. For example, in case of fork, parent and child process writes simultaneously to the same file using fprintf.

Notes: The log file is open once

My questions:

  1. Is there a chance of different log messages overwriting each other?
  2. Is concept of atomic operation applicable to multiple processes? (Is it guaranteed that a called to fprintf in a process will complete entirely before another process calls fprintf?)

In short: Can I get away with just fprintf without using any locking mechanism and have a logging api that is safe to write simultaneously to the same file from multiple processes?

  • "*Since fprintf is an atomic operation*" is it? Not aware that the Standard specifies this. POSIX on the other hand says that `fprintf()` is thread-safe though. – alk Apr 17 '20 at 13:32
  • 1
    @alk: C 2018 7.21.2 7: “Each stream has an associated lock that is used to prevent data races when multiple threads of execution access a stream, and to restrict the interleaving of stream operations performed by multiple threads…” – Eric Postpischil Apr 17 '20 at 13:35
  • @EricPostpischil: Interesting. Is this new with C18? – alk Apr 17 '20 at 13:37
  • @al: Nothing is new in C 2018; it is intended to contain only “technical corrections and clarifications.” However, I see this wording in a C 2011 draft but not in a C 2007 draft. – Eric Postpischil Apr 17 '20 at 13:42
  • Speaking to the question, streams are a C feature internal to a program execution. They are connected to external files, the stream-locking guarantee does not extend to files, and I do not see a guarantee for file locking in the C standard and would not expect one. With typical Unix behavior without effort to synchronize or lock, I would expect two processes that periodically write to a file to interfere destructively on an effectively random basis. – Eric Postpischil Apr 17 '20 at 13:44
  • 1
    All of the wording about thread safety in ISO C was added in C2011, on account of _threads_ were added to ISO C in C2011. Prior to that the C abstract machine was single-threaded so they couldn't even talk about it. – zwol Apr 17 '20 at 14:03

0 Answers0