Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until the file is closed

Tags:

linux

I have an external process that start a write to a file.
How do I write script that waits until the file is closed (when the other process done with the writing).

like image 512
shaiis.com Avatar asked Mar 08 '12 14:03

shaiis.com


1 Answers

There are several ways to achieve this:

  • If you can, start the process from your script. The script will continue when the process terminates and that means it can't write any more data to the file.

  • If you can't control the process but you know that the process terminates after writing the file, you can find out the process ID and then check if the process is still running with kill -0 $PID. If $? is 0 afterwards, the process is still alive.

  • If that's not possible, then 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 slow, though.

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

The rename makes sure that everyone else either sees the whole file with all the data or nothing.

like image 122
Aaron Digulla Avatar answered Sep 29 '22 01:09

Aaron Digulla