I want to synchronize access to files. I am using Linux and g++.
I would like to lock the file by using the function flock().
I developed 2 tests applications writing and reading to/from the same file.
They both call flock() with LOCK_SH.
The writer starts first, writes and then sleeps. The second app starts later.
I was expecting to see the reader app blocking when it calls flock() since the writer process didn’t release the lock.
Is this the right expectation or do they block ONLY when read() and write() are called concurrently i.e. at the same exact time?
What have I misunderstood?
PROG A PROG B
-open file
-flock -open file
-write -sleep 5
-sleep 1000 -flock ** expected to block ?? **
-close -read data
flockwould only block if at least one process uses it withLOCK_EX:In general you should use shared locks for read and exclusive for write or read/write.