0

I have a script which locks a file to avoid concurrent access to it, How can I execute this same script from two different terminals synchronously, to check if it works?

Here is the script

#!/bin/bash

(
  flock -xn 200
  trap 'rm /tmp/test_lock.txt' 0
  RETVAL=$?
  if [ $RETVAL -eq 1 ]
  then
    echo $RETVAL
    echo  "file already removed"
    exit 1
  else
    echo "locked and removed"
  fi
) 200>/tmp/test_lock.txt
roaima
  • 107,089
  • 14
  • 139
  • 261
Rob
  • 101

1 Answers1

0

You can't execute them synchronously, but by placing a sleep 60 inside the bracketed lock section you can demonstrate to yourself that only one instance can run simultaneously (at the same time). Or not.


You'll notice that what you have does not work. This is because you delete the lock file, which means that any new process trying to obtain the lock does so on a different file to the one that already holds the lock.

roaima
  • 107,089
  • 14
  • 139
  • 261