How to wait until a file is closed

I have an external process that starts writing to a file.
How to write a script that waits until the file is closed (when another process is executed with the record).

+6
source share
5 answers

There are several ways to achieve this:

  • If you can, start the process from your script. The script will continue when the process ends, which means that it cannot write more data to the file.

  • If you cannot control the process, but know that the process ends after writing the file, you can find out the process identifier, and then check whether the process continues to work with kill -0 $PID . If $? - 0 , then the process is still alive.

  • If this is not possible, you can use lsof -np $PID to get a list of all open files for this process and check if your file is in the list. This is somewhat slower.

[EDIT] Note that all of these approaches are somewhat fragile. The correct solution is for the external process to write the file using a temporary name and then rename it as soon as it is done.

Renaming ensures that everyone else either sees the entire file with all the data, or nothing.

+3
source

A simple way: let the script execute the program and wait for the end.

+2
source

This is not good and it makes me feel dirty writing it down ... /tmp/foo.txt is a verified file ...

 #!/bin/bash until [ "$( find /proc/*/fd 2> /dev/null | xargs -i{} readlink {} | grep -c '^/tmp/foo.txt$' )" == "0" ]; do sleep 1; done; 
+1
source

Create a small C program using inotify . The program should:

  • Create an inotify instance.
  • Add chat to the instance for the IN_CLOSE_WRITE event for the file of interest.
  • Wait for the event.
  • Exit with the appropriate code.

Then in the script, call the program from the file path as an argument.

You can expand this by adding a timeout argument and specifying various events.

+1
source

Loop until the file is stable, this should work if you are expecting experiment results (so you don't need real-time event processing):

 EXPECTED_WRITE_INTERVAL_SECONDS=1 FILE="file.txt" while : ; do omod=$(stat -c %Y $FILE) # echo "OLD: $omod" sleep $EXPECTED_WRITE_INTERVAL_SECONDS nmod=$(stat -c %Y $FILE) # echo "NEW: $nmod" if [ $omod == $nmod ] ; then break fi done 
0
source

Source: https://habr.com/ru/post/910244/


All Articles