benrush
benrush

Reputation: 321

Is fwrite() atomic when applied to multiple FILE*, same file descriptor?

  1. using fileno() to get the actual file descriptor of stdout.
  2. using fdopen() to create two different FILE* structure, named a and b.
  3. creating two threads, name A and B, using fwrite() to write some contents to a and b.

Question:

  1. Is this operation correct, or recommended?
  2. If A thread is writing 123, B thread is writing 456, is it possible that 142536 got output in the stdout?

Upvotes: 1

Views: 81

Answers (2)

Wiimm
Wiimm

Reputation: 3572

Possibly interesting if logging: If a file was opened with open() and mode O_APPEND, then (extract of man open):

O_APPEND: The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2). The modification of the file offset and the write operation are performed as a single atomic step.

If using fopen() with mode a or a+, then mode O_APPEND is set.

Upvotes: 0

tl-photography.at
tl-photography.at

Reputation: 125

Maybe have a look here: fopen and fwrite to the same file from multiple threads

Better define another thread, which is taking control over the file and implement a queue like structure that other tasks can fill with data.

The file thread will then pop (think FIFO) data from the structure and write it to the file.

Upvotes: 1

Related Questions