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

Deleted picture Deleted · Sep 26, 2011 · Viewed 15k times · Source

I have a process opening a file in append mode. In this case it is a log file. Sample code:

int main(int argc, char **argv) {
    FILE *f;
    f = fopen("log.txt", "a");
    fprintf(f, "log entry line");
    fclose(f);
}

Two questions:

  1. If I have multiple processes appending to the same file, will each log line appear distinctly or can they be interlaced as the processes context switch?
  2. Will this write block if lots of processes require access to the file, therefore causing concurrency problems?

I am considering either doing this in its simplest incarnation or using zeromq to pump log entries over pipes to a log collector.

I did consider syslog but I don't really want any platform dependencies on the software.

The default platform is Linux for this btw.

Answer

cnicutar picture cnicutar · Sep 26, 2011

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.