Is fwrite atomic?

2019-04-05 18:21发布

问题:

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?

回答1:

It can be mixed.

If you have more than one thread/process writing to the same file, you need to use locking.

An alternative is to send log messages to a dedicated service/thread. An excellent tool to adopt is syslog, which is surely installed on all unixes and can be run on Windows.



回答2:

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.



回答3:

From "man flockfile" on Debian lenny, the stdio functions are thread-safe.

There're thread-unsafe stdio functions, "man unlocked_stdio" for more details.

You can get more information from the man page.



回答4:

fwrite for visual studio locks the calling thread and is therefore thread-safe



标签: c file-io atomic