shell中确保只有一个进程在执行

shell中实现保证同一时间内只有一个进程在实现:

 

1.lockf命令

 

2.简单实现:

i=`ps -ef|grep [n]ew_mvbackup|wc -l`if [ $i -gt 1 ];
then
echo "wait for the other mvbackup finish!"
exit -1
else

#do something here

 

3.另外一种实现:

lock_on()

{

   local f=$1

   local freefd=6 ## do not use fd 5

   ## make sure the file be there

   mkdir -p "$( dirname $f )"

   touch "$f"

   ## find a free fd

   while (( freefd <= 9 )); do

     [[ -L /dev/fd/$freefd ]] || break

     (( freefd++ ))

   done

 

(( freefd == 10 )) && return 1

## open the lock file

   eval "exec $freefd< /"$f/"" }

 

is_locked()

{

   local f=$1

  fuser "$f" &> /dev/null

}

lock="/tmp/.$( basename $0 ).lock"

is_locked "$lock" && exit 1

lock_on "$lock"

 

## do something here

你可能感兴趣的:(shell,File)