I have two scripts running in python on the same machine as endless loops, they are monitoring some values constantly. They communicate via file.txt
B adds messages to a file.txt so they pile up. When A checks file.txt it reads them in and empties the file.txt
A
while true:
Open file.txt if B is not using it or when B is done
f = open('file.txt', 'r+')
message=f.read() #read all the messages that have accumulated
f.truncate() #delete the messages
f.close()
---use message do other things
B
while true:
---Gather information for the message
Open file.txt if A is not using it or when A is done
f = open('file.txt’,’a’)
f.write(‘message’)
f.close()
The pickle is that I want each of the scripts to open file.txt only when the other one is not using it, or wait for it to stop using. So while B is writing and A wants to read then B will halt for short time and then continue.
There is no need to sync the two. Actually I want them to be in-dependant, not threaded or run in parallel. For example B can go to cycles while A only goes one or vice versa. Or if A is delayed for some reason the messages would just pile up in file.txt since B continues running.
I have read about putting lock on the file. Would it be possible to do in each of the scripts:
A
if "file locked by B":
wait for unlock
lock file
open file
read from file
empty file
close file
unlock file
What tools would one use for "Wait for unlock" and "file locked by B" and "lock file"?