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

后端 未结 9 1940
悲&欢浪女
悲&欢浪女 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:39

    I had recently the same question and found from above that kill -0 is best for my case:

    echo "Starting process..."
    run-process > $OUTPUT &
    pid=$!
    echo "Process started pid=$pid"
    while true; do
        kill -0 $pid 2> /dev/null || { echo "Process exit detected"; break; }
        sleep 1
    done
    echo "Done."
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 00:45

    For a method that does not suffer from parsing bugs and race conditions, check out:

    • BashFAQ/045 - How can I ensure that only one instance of a script is running at a time (mutual exclusion)?
    0 讨论(0)
  • 2021-02-06 00:55

    You can use pidof -x if you know the process name, or kill -0 if you know the PID.

    Example:

    if pidof -x vim > /dev/null
    then
        echo "Vim already running"
        exit 1
    fi
    
    0 讨论(0)
  • 2021-02-06 00:56
    pgrep -f yourscript >/dev/null && exit
    
    0 讨论(0)
  • 2021-02-06 00:57

    This is how I do it in one of my cron jobs

    lockfile=~/myproc.lock
    minutes=60
    if [ -f "$lockfile" ]
    then
      filestr=`find $lockfile -mmin +$minutes -print`
      if [ "$filestr" = "" ]; then
        echo "Lockfile is not older than $minutes minutes! Another $0 running. Exiting ..."
        exit 1
      else
        echo "Lockfile is older than $minutes minutes, ignoring it!"
        rm $lockfile
      fi
    fi
    
    echo "Creating lockfile $lockfile"
    touch $lockfile
    

    and delete the lock file at the end of the script

    echo "Removing lock $lockfile ..."
    rm $lockfile
    
    0 讨论(0)
提交回复
热议问题