flock(), then fgets(): low-level locks, then stdio read/write library functions. Is it possible?

StackOverflow https://stackoverflow.com/questions/10259752

  •  02-06-2021
  •  | 
  •  

Question

I'm writing a server web.

Each connection is served by a separate thread, so I don't know in advance the number of threads.

There are also a group of text files (don't know the number, too), and each thread can read/write on each file.

A file can be written by just one thread a time, but different threads can write on different files at the same time.

If a file is read by one or more threads (reads can be concurrent), no thread can write on THAT file.

Now, I noticed this (Thread safe multi-file writing) solution, but I'd like also to use functions as fgets(), for example.

So, can I flock() a file, and then use a fgets() or another stdio read/write library function?

Was it helpful?

Solution

First of all, use fcntl, not flock. The latter is a non-standard, deprecated BSD function and does not work with NFS and possibly other filesystems. fcntl locking on the other hand is POSIX standard and is intended to work everywhere.

Now if you want to use file-level reader-writer locking mixed with stdio, it will work, but you have to take some care to ensure that buffering does not break your assumptions about locks. The method I'm about to explain is not the only one, but I believe it's the clearest/simplest:

When you want to operate on one of your files with stdio, obtaining the correct type of lock (read or write, aka shared of exclusive) should be the first thing you do after fopen. Use fileno to get the file descriptor number and apply the lock to it. After that, perform your entire read or write operation. Do not make any attempt to unlock the file; instead, call fclose to close the file and let it be implicitly unlocked when it's closed. Otherwise you may release the lock while unbuffered data is still unwritten, or later read data that was buffered before the lock was released, that's no longer valid after the lock is released.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top