How to make file lock with bash

假装没事ソ 提交于 2019-12-11 06:39:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!