Quote:
Originally Posted by
methyl
After creating the file append your shell's process id. Read back the file and check the process id to be 100% sure that your instance holds the interlock before processing, otherwise back off.
Depends on what you mean for "back off".
Suppose that while you write the pid another process is doing the same. This results in the other pid appearing inside the file before or after your pid, the position does not matter here.
Then you check and see another pid:
- You wait, leaving in place your pid. Deadlock: both processes waiting for the other pid to disappear.
- You delete your pid (not a trivial task) and wait for some interval, then you write your pid again and check. The other process is doing the same, therefore it is likely that both processes again see another pid and have to wait again. A pseudo-random wait interval would take care of the problem... it reminds me of Ethernet collision detection. It would perhaps work, but it seems just too involved.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Ok, now I got it: the serialization protocol dictates that the pid appearing in line 1 of the interlock file is the one whose process is allowed to go on, while the other processes are inside a wait-and-check loop (well, perhaps it is smarter to just
wait $pid1 where pid1 is read from line 1); when the process ends, it removes its pid; then another pid is in line 1... and so on, until the pid queue is empty.
Not bad. Still a bit involved though.
You have to be absolutely sure that the script cannot end without having removed its pid from the queue. An exit handler implemented with
trap would be enough, but a SIGKILL would bypass the trap.