#!/bin/bash

# Usage:  deadlock <1st lockfile name> <2nd lockfile name> <3rd lockfile name> ...
# Program cannot proceed (is "locked") if any of the lockfiles exist already.
# Provided they don't, program will create them,
# preventing another copy of this program from running till this copy is done.
# When done, this copy deletes the lockfiles freeing any such other copy to go ahead.

# if this copy is to create 2 lockfiles,
# and another copy runs to create the same 2 but in opposite order (given as such on commandline),
# and the other copy launches within 3 seconds of this one, a deadlock results


lock-a-file()
{
echo "I will now try to create file \"$1\""
while true
do
	if [ ! -f $1 ]; then		# if the file does not exist
		touch $1		# create it
		echo " Created \"$1\" successfully"
		break
	else
		echo -n "waiting (for $1)  "; sleep 1
		continue
	fi
done
echo
}

if [ $# -eq 0 ];then
	echo "You must supply at least one file name."
	exit 1
fi

FILELIST="$@"
echo -e "\nI must secure the following files before I am allowed to work: $FILELIST\n"

for file in $FILELIST; do
	lock-a-file $file
	sleep 3
done

for i in {1..10};do echo "doing work! "; sleep 1; done; echo "Finished working."; echo

for file in $FILELIST; do
	rm $file
	echo " Removed \"$file\""
	sleep 6
done
