How to check in a bash script if something is running and exit if it is

后端 未结 9 1955
悲&欢浪女
悲&欢浪女 2021-02-06 00:24

I have a script that runs every 15 minutes but sometimes if the box is busy it hangs and the next process will start before the first one is finished creating a snowball effect.

9条回答
  •  失恋的感觉
    2021-02-06 00:40

    To expand on what @bgy says, the safe atomic way to create a lock file if it doesn't exist yet, and fail if it doesn't, is to create a temp file, then hard link it to the standard lock file. This protects against another process creating the file in between you testing for it and you creating it.

    Here is the lock file code from my hourly backup script:

    echo $$ > /tmp/lock.$$
    if ! ln /tmp/lock.$$ /tmp/lock ; then 
            echo "previous backup in process"
            rm /tmp/lock.$$
            exit
    fi
    

    Don't forget to delete both the lock file and the temp file when you're done, even if you exit early through an error.

提交回复
热议问题