如何使用bash锁定文件 [英] How to make file lock with bash

查看:218
本文介绍了如何使用bash锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务要从远程服务器中同步目录

I have a task to rsync a dir from remote server

rsync -av root@s0.foo.com:/srv/data/ /srv/data/ 

为使其正常运行并避免脚本"reEnter"问题,我使用rsync progress的pid创建了文件锁"in_progress",它指示程序是否仍在运行.

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
}

使用此功能来判断rsync进度是否仍在运行:

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
}

我可以通过此方法获得传递给函数lock的pid

I can get the pid to pass to function lock with this

$!

我必须放置rsync进度背景来获取rsync的pid,所以我明白了

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 $!

但是当rsync进度完成时,我应该rm锁定文件
我尝试过了

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 $!

...然后看来我获得的pid不是rsync进度的pid:-(

... then it seems the pid I got is not the pid of rsync progress :-(

推荐答案

如果要防止同时执行,flock是一个不错的工具:

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/" &

这篇关于如何使用bash锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆