I am developing a program that will read files created by another program and process them. When I find a new file in the directory of interest, then I process that file as required.
Then I realized that it will take a while for the file to be written and my algorithm will detect the file and process it before it has been written.
I figured that the other process will have a lock on the file, and I should be able to detect that lock and wait until the lock has been released. I checked out the stat command, but it does not seem to help. Is there a method to check if another program is using the file?
It looks promising, but the first line in the documentation says:
A simple utility tool for creating advisory pidfiles (lock files).
Perhaps I can only create the advisory pidfile if another process is not locking the file? Then it should work. So far I have not seen an example and have not figured out how to use it.
In my case I am reading the file with some code that does not check for locks. A simple solution is to use a try catch block, and include a move statement (mv) before processing the file. The mv will error and the try catch block will catch the error.