Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is fwrite atomic?

Tags:

c

file-io

atomic

A simple question:

I need to add some logging to my program.

If two processes use "fwrite" on the same file but not the same file descriptor will the written log messages be atomic or mixed. Is there a length limit?

Is it defined ANSI-C behaviour or implementation defined? If the later what is on MacOSX, Linux and Windows MSVC?

like image 423
Lothar Avatar asked Feb 08 '10 09:02

Lothar


People also ask

How does fwrite work?

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

Does fwrite use write?

fwrite() — Write Items. Threadsafe: Yes. The fwrite() function writes up to count items, each of size bytes in length, from buffer to the output stream . The fwrite() function returns the number of full items successfully written, which can be fewer than count if an error occurs.


1 Answers

After doing some research and I've found the following in this link:

POSIX standard requires that C stdio FILE* operations are atomic. POSIX-conforming C libraries (e.g, on Solaris and GNU/Linux) have an internal mutex to serialize operations on FILE*s.

It looks like that calls should be atomic, but it depends on your platform. In same link, there is also another paragraph that lets you think that the programmer should take care:

So, for 3.0, the question of "is multithreading safe for I/O" must be answered with, "is your platform's C library threadsafe for I/O?" Some are by default, some are not; many offer multiple implementations of the C library with varying tradeoffs of threadsafety and efficiency. You, the programmer, are always required to take care with multiple threads.

Also, as you have two different FILE* in two different processes, I think you have no choice.

like image 161
yeyeyerman Avatar answered Oct 20 '22 21:10

yeyeyerman