lock-and-run.sh 773 B

1234567891011121314151617181920212223242526272829303132333435
  1. #! /bin/sh
  2. # Shell-based mutex using mkdir.
  3. lockdir="$1" prog="$2"; shift 2 || exit 1
  4. # Remember when we started trying to acquire the lock.
  5. count=0
  6. touch lock-stamp.$$
  7. trap 'rm -r "$lockdir" lock-stamp.$$' 0
  8. until mkdir "$lockdir" 2>/dev/null; do
  9. # Say something periodically so the user knows what's up.
  10. if [ `expr $count % 30` = 0 ]; then
  11. # Reset if the lock has been renewed.
  12. if [ -n "`find \"$lockdir\" -newer lock-stamp.$$`" ]; then
  13. touch lock-stamp.$$
  14. count=1
  15. # Steal the lock after 5 minutes.
  16. elif [ $count = 300 ]; then
  17. echo removing stale $lockdir >&2
  18. rm -r "$lockdir"
  19. else
  20. echo waiting to acquire $lockdir >&2
  21. fi
  22. fi
  23. sleep 1
  24. count=`expr $count + 1`
  25. done
  26. echo $prog "$@"
  27. $prog "$@"
  28. # The trap runs on exit.