Reputation: 159
I am using Flock to get an exclusive lock on a text file and write something in it, before doing that I want to check if some other process has any kind of lock on that file, if so then I would like to do something else rather be in the queue which is default action in flock.
So, I want something like
if locked; then
do something
else
(
flock -e 200
echo "In critical section"
echo text >> file.txt
echo text added to File
) 200>file.txt
is there a way in bash to check this? I have looked into lsof but I am not able to arrive at solution.
Upvotes: 1
Views: 5226
Reputation: 132
Try using ...
( flock -n 200 || exit 1
echo "In critical section"
echo text >> file.txt
echo text added to File
) 200>file.txt
The '-n' flag will prevent blocking, and the exit code will be '1' if the lock was not obtained.
Upvotes: 1