I'd like to create a temporary file that will be read by multiple scripts after its creation, but I don't have an easy way of monitoring when the last script finishes reading this temporary file to delete it (it may be a different script each time). I'd like to know if there's a standard way of solving this problem with command-line tools that will autodelete this file when it passes a specific interval of time without being read by any program, is it possible? Or the only way to solve this problem would be to figure out a way of knowing when the last script finishes reading this file for deleting it?
Using inotifywait, you can add the following to your scripts that access the file.
if ! inotifywait $FILE -t $SECONDS >/dev/null 2>&1 then rm $FILE fi &
The script will spawn a process that waits until something accesses $FILE.
if something does, it does nothing and exits.
if the timeout is reached after $SECONDS, it will remove the file
alternatively using a seperate script, that you run at creation of the file
while inotifywait $FILE -t $SECONDS >/dev/null 2>&1 do sleep 1 done rm $FILE
it will loop whenever the file is accessed,
if nothing accesses it within the timeout, it breaks and removes the file.
Based on taiyu's answer using
inotifywait I've created a
node.js solution to this problem... It required more details than I expected when I asked it. Sorry if that's not the right place for posting node.js code but the asynchronous nature of the language made things simpler for me... My solution is the following:
Basically, I used
inotifywait as a basis for solving the problem... I just need to execute this script after creating the temporary file and it will erase the file after all other programs finish reading the file (after 10 seconds).
OBS: My problem trying to solve it with
bash is that when I make a function run as a process with
& I lose control of the new values of global variables inside that function. So I couldn't get the
counter state using the same logic that I've used on
node.js... If someone knows a workaround for this, feel free to write in the comments here. :)