We all know that Linux/Unix will automatically block attempts to write to a file that currently open for writing by another process. But is it possible to block/lock read access to a file if another process has it open for writing? I've got two different scripts, both start at random times and run various times during the day: one script overwrites a particular file; the other one reads from that file. I want the second one to block(wait) or fail if the first one has the file open.
The flock(1) utility may do what you want
Take out a write lock on the file when you want to overwrite it
flock -x /path/to/lockfile somecommand file
Have the other command check for the lock.
flock -n /path/to/lockfile anothercommand file
If the file is locked then you get an exit code of 1 otherwise it's yours and you can do what you want with it
Since you have complete un-synchronize running.. You could do something simple which is to have the "writing" process create the new file with a temp name say .tmp so if the file it will create is output1.txt it would work in output1.txt.tmp.
Once the writer is done the last thing it does is a mv command.
From here you can do two things. One have the reader not care because since the tmp file is a different inode, the mv will not hurt it (Linux will keep it alive as long as it has a consumer) and the next read will have the new file..
(as long as it would not hurt you to run with the old file one last time).
The other option is that the reader looks for the tmp file and block while that file exists (this becoming a sort of lock file).
Not being eligible (yet :-)) to comment on a question let me warn readers on the question's false statement, through "answering":
My proof bases on
man 2 open,write
that do not discourage from attempting which of course has been done by myself. For further learning on the question I recommend a decent discussion.If my warning is still unsuitable (does not answer the asker's question) instead of deleting it I suggest to copy it by someone creditable under the question comments section. After verification of course. Thank you.