loop_times_before_check=100
if [ -n "$1" ];then
limit=$1
else
# default concurrence is 1
limit=1
fi
number_of_running=0
counter=0
while :;do
#check stale token, which owner is died unexpected
if [ "$counter" -eq "$loop_times_before_check" ]; then
counter=0
for pid in `cat token_file`;do
pgrep $pid
if [ $? -ne 0 ]; then
#remove lock
printf "s/ $pid//\nwq\n"|ed -s token_file
number_of_running=`expr $number_of_running - 1`
fi
done
fi
counter=`expr $counter + 1`
#
if [ "$number_of_running" -ge "$limit" ];then
# token is all given out. bypass all request until a instance to give one back
pid=`sed -n '/stop/ {s/\([0-9]\+\) \+stop/\1/p;q}' /tmp/p-aquire`
if [ -n "$pid" ]; then
# get a token returned
printf "s/ $pid//\nwq\n"|ed -s token_file
number_of_running=`expr $number_of_running - 1`
continue
fi
else
# there is still some token to give out. serve another request
read pid action < /tmp/p-aquire
if [ "$action" = stop ]; then
# one token is given back.
printf "s/ $pid//\nwq\n"|ed -s token_file
number_of_running=`expr $number_of_running - 1`
else
# it's a request, give off a token to instance identified by $pid
printf " $pid" >> token_file
number_of_running=`expr $number_of_running + 1`
fi
fi
done
#!/bin/sh
# second to wait that the ditributer gives off a token
a_while=1
if [ ! -p /tmp/p-aquire ]; then
printf "cannot find file /tmp/p-aquire\n" >&2
exit 1
fi
# try to aquire a token
printf "$$\n" >> /tmp/p-aquire
sleep $a_while
# see if we get one
grep "$$" token_file
if [ $? -ne 0 ]; then
# bad luck. :(
printf "no token free now, exitting...\n" >&2
exit 2
fi