Can multiple processes append to a file using fopen without any concurrency problems? Can multiple processes append to a file using fopen without any concurrency problems? unix unix

Can multiple processes append to a file using fopen without any concurrency problems?


I don't know about fopen and fprintf but you could open the file using O_APPEND. Then each write will go at the end of the file without a hitch (without getting mixed with another write).

Actually looking in the standard:

The file descriptor associated with the opened stream shall be allocated and opened as if by a call to open() with the following flags:

a or ab          O_WRONLY|O_CREAT|O_APPEND

So I guess it's safe to fprintf from multiple processes as long as the file has been opened with a.


The standard (for open/write, not fopen/fwrite) states that

If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.

For fprintf() to be used, you have to disable buffering on the file.


You'll certainly have platform dependencies since Windows can't handle multiple processes appending to the same file.

Regarding synchronization problems, I think that line-buffered output /should/ save you most of the time, i.e. more than 99.99% of short log lines should be intact according to my short shell-based test, but not every time. Explicit semantics are definitely preferable, and since you won't be able to write this hack system-independently anyway, I'd recommend a syslog approach.