【问题标题】:Background rsync and pid from a shell script来自 shell 脚本的后台 rsync 和 pid
【发布时间】:2016-06-10 13:09:04
【问题描述】:

我有一个执行备份的 shell 脚本。我将此脚本设置在 cron 中,但问题是备份很重,因此可以在第一个 rsync 结束之前执行第二个 rsync。 我想在脚本中启动 rsync 然后获取 PID 并编写一个文件,该脚本检查进程是否存在(如果该文件存在或不存在)。 如果我将 rsync 放在后台,我会得到 PID,但我不知道如何知道 rsync 何时结束,但是,如果我设置 rsync(无背景),我无法在进程完成之前获得 PID,所以我不能写文件带有 PID。

我不知道“拥有 rsync 控制”以及何时完成的最佳方式是什么。

我的脚本

#!/bin/bash
pidfile="/home/${USER}/.rsync_repository"

if [ -f $pidfile ];
then
        echo "PID file exists " $(date +"%Y-%m-%d %H:%M:%S")
else
        rsync -zrt --delete-before /repository/ /mnt/backup/repositorio/ < /dev/null &
        echo $$ > $pidfile
        # If I uncomment this 'rm' and rsync is running in background, the file is deleted so I can't "control" when rsync finish
        # rm $pidfile 
fi

谁能帮帮我?!

提前致谢!! :)

【问题讨论】:

  • @user2181624 我不知道我要等多久:S 我认为这不是最好的方法。
  • 您无需知道要等待多少时间。查看 bash 手册页(因为它很长,(并且单词 wait 出现了无数次)转到手册页的末尾,向后搜索“SHELL BUILTIN”,然后向前搜索“等待”。

标签: linux bash shell rsync


【解决方案1】:
# check to make sure script isn't still running
# if it's still running then exit this script

sScriptName="$(basename $0)"

if [ $(pidof -x ${sScriptName}| wc -w) -gt 2 ]; then 
    exit
fi
  • pidof 查找进程的 pid
  • -x 告诉它也寻找脚本
  • ${sScriptName} 只是脚本的名称...您可以对其进行硬编码
  • wc -w 按字数返回字数
  • -gt 2 运行的实例不超过一个(实例加 1 用于 pidof 检查)
  • 如果有多个实例在运行,则退出脚本

让我知道这是否适合你。

【讨论】:

    【解决方案2】:

    像这样测试 pid 文件的存在和正在运行的进程的状态:

     #!/bin/bash
    
     pidfile="/home/${USER}/.rsync_repository" 
     is_running =0
    
     if [ -f $pidfile ];
     then
        echo "PID file exists " $(date +"%Y-%m-%d %H:%M:%S")
        previous_pid=`cat $pidfile`
        is_running=`ps -ef | grep $previous_pid | wc -l` 
     fi
    
     if [ $is_running -gt 0 ]; 
     then
        echo "Previous process didn't quit yet"
     else
        rsync -zrt --delete-before /repository/ /mnt/backup/repositorio/ < /dev/null &
        echo $$ > $pidfile
     fi
    

    希望对你有帮助!!!

    【讨论】:

    • 听起来不错,但我不明白脚本如何知道进程何时结束。该脚本会查找 PID,但它不会删除 PID 文件,因此它总是会运行,不是吗?谢谢!
    • @jask 脚本不会等待进程结束。但是,这里的技巧是记录最后启动的脚本进程的 PID,然后在后续运行时,只需检查最后记录的 PID 是否存在(ps -ef | grep $previous_pid | wc -l)。如果最后一个进程仍在运行,则脚本退出而不启动新的,否则启动新的脚本并记录其 PID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多