I have a log file that is going to be updated by a shell script. This shell script has a number of operations and updates the file after each operation, saying the operation has finished. Now, I need to ‘listen’ on this file from a servlet and send response back to the end user in the same fashion as the logging happens (i.e. operation A finished, operation B finished and so on). Now if both the servlet and the shell script try to open the file at the same time I am sure I will get some error. In java I guess I can handle it as IOException and keep trying to read the file, so that it works when the shell script is not updating the file. How should I handle this in shell script? Will it help if I open the file in read only mode in java? Also note that the shell script only writes and doesn’t read and the servlet only reads and doesn’t write.
Also, suggestions welcome on a better way of implementing this workflow.
Since you can’t use the WatchService, you could poll the files last modification using
file.lastModified().If you do this periodically, you can compare the results and if they changed, the file was modified by the shell script. It might be necessary to create a new File object everytime you poll, but since the file isn’t opened for reading at all no access problems will occur.
However, even if you open the file and compare its contents you should not experience any access problems, unless your shell opens the file with exclusive access.