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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With