简体   繁体   English

Bash脚本检查是否正在运行

[英]Bash script to check if running

I have the following in my crontab to sync my folders on the servers as they are run on round robin DNS settings it syncs every minute. 我的crontab中有以下内容,用于在服务器上同步我的文件夹,因为它们在每分钟同步的循环DNS设置上运行。

* * * * * rsync -ar --delete -e ssh user@skynet.rizzler.se:/home/user/folder1/ /home/user/folder1/ >/dev/null 2>&1
* * * * * rsync -ar --delete -e ssh user@skynet.rizzler.se:/home/user/folder2/ /home/user/folder2/ >/dev/null 2>&1

This Rsync works for small files, but it's getting bigger so I am wondering how I can get this into a script, put that script into my crontab and each time the script is run, it will check if it's running. 这个Rsync适用于小文件,但是它越来越大,所以我想知道如何将其放入脚本中,将该脚本放入crontab中,每次运行该脚本时,都会检查它是否正在运行。 If the script is running, it will do nothing; 如果脚本正在运行,它将什么都不做; if it's not running, it should go ahead and start the rsync. 如果未运行,则应继续并启动rsync。

Anyone know how I can do this? 有人知道我该怎么做吗?

As swornabsent noted in the comments, you can use file-based locks , though that SO link identifies some good reasons not to use it. 正如评论中提到的,您可以使用基于文件的锁 ,尽管该SO链接标识了一些不使用它的充分理由。 See this SO question about quick-and-dirty locking in shell scripts , which has a great answer about advantages to directory-based locks instead. 请参阅此有关shell脚本中快速脏锁的问题 ,该问题对基于目录的锁的优势有很好的回答。

To identify whether a process is running, you may also choose to use pgrep , though that may not be a good idea in the general case due to the time after the check and before the process starts up. 要确定某个进程是否正在运行,您还可以选择使用pgrep ,尽管在一般情况下,由于检查之后和启动之前的时间,这可能不是一个好主意。

You could write the script's PID into a file with echo $$ > /var/run/rsync_job.pid 您可以将脚本的PID写入echo $$ > /var/run/rsync_job.pid的文件中

Then when you start you could first check if that file exists, and if it does read the PID from it and see if that process still exists like 然后,当您启动时,您可以首先检查该文件是否存在,以及是否确实从文件中读取了PID,然后查看该进程是否仍然存在,例如

if ps -p $PID &>/dev/null; then
    # it's still running
    exit
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM