问题
I have a task to rsync a dir from remote server
rsync -av root@s0.foo.com:/srv/data/ /srv/data/
To make it run regularly and avoid Script "reEnter" issue, I create a file lock "in_progress" with rsync progress's pid, which indicate whether the program is still running.
lock(){
echo $1 > in_progress
}
Using this function to judge whether the rsync progress is still running:
is_running(){
pid=$(cat in_progress)
return ps aux | awk '{print $2}' | grep $pid
}
I can get the pid to pass to function lock
with this
$!
I had to put the rsync progress background to get the pid of rsync, so I get this
rsync -av root@s0.foo.com:/srv/data/ /srv/data/ &
lock $!
but when rsync progress is done, I should rm the lock file
I tried this
rsync -av root@s0.foo.com:/srv/data/ /srv/data/ && rmLock &
lock $!
... then it seems the pid I got is not the pid of rsync progress :-(
回答1:
If you want to prevent simultaneous executions , flock is a nice tool:
$ flock -n /path/to/lock/file -c "rsync -av root@s0.foo.com:/srv/data/ /srv/data/" &
回答2:
( rsync -av root@s0.foo.com:/srv/data/ /srv/data/ && rmLock ) &
Also
[ -d /proc/$pid ] && …
回答3:
I just find a way to solve this, using wait
rsync -av root@s0.foo.com:/srv/data/ /srv/data/ &
pid=$!
lock $pid
wait $pid
rmLock $pid
thanks to tijagi, I found a more elegant way to judge whether a progress is running.
来源:https://stackoverflow.com/questions/25863930/how-to-make-file-lock-with-bash