0

I have a process that creates a lockfile ~/process.lock

I wanted to execute a command as soon that process ended, so i wrote

while [ -e ~/process.lock ]
do
:
done
#do stuff after process has ended

Apparently this prevented process.lock being deleted by the parent process. Did this happen? If yes, why? and what is the correct way to do this.

kabZX
  • 137
  • 3
  • What OS? In most Unix environments, I would not expect `-e` to put any kind of lock on its argument that prevents it from being removed. – chepner Sep 28 '14 at 12:49
  • Sorry - missed that. Lubuntu 14.04. Yes i expected no locking, but I was later wondering if it would not have happened if I put a sleep 1 or some such in the loop? – kabZX Sep 28 '14 at 16:00
  • The main problem is not in the spin lock, but in the race condition. Your code is simply not correct because the file could be created by another process between the `test` invocation and the beginning of the `while` loop's body- – tripleee Sep 30 '14 at 06:55
  • possible duplicate of [Quick-and-dirty way to ensure only one instance of a shell script is running at a time](http://stackoverflow.com/questions/185451/quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at) – tripleee Sep 30 '14 at 06:55
  • See also http://stackoverflow.com/questions/6870221/is-there-any-mutex-semaphore-mechanism-in-shell-scripts – tripleee Sep 30 '14 at 06:56

1 Answers1

0

Indeed, the problem is probably not the -e test, but the tight loop, delaying anything else from happening, especially on a system with only a single (logical) core. Adding sleep will undoubtedly help, and you may find that the sleep command accepts arguments less than 1, so you can notice the file disappear fairly quickly.

Nick Russo
  • 1,522
  • 10
  • 13
  • 1
    I just created a test case with two commands: `echo "Start"; while [ -e lockfile.lock ]; do : ; done; echo "No lockfile";` and `touch lockfile.lock; sleep 5; rm lockfile.lock; echo "Done";` but I'm not able to reproduce the problem anymore. The original problem was on an old, crusty single CPU machine, so could have been that. Anyway, i'll mark this as accepted to close the issue. Thanks all. – kabZX Sep 29 '14 at 04:47