How do I make sure my bash script isn't already running?

后端 未结 13 841
無奈伤痛
無奈伤痛 2020-12-31 05:56

I have a bash script I want to run every 5 minutes from cron... but there\'s a chance the previous run of the script isn\'t done yet... in this case, i want the new run to j

13条回答
  •  离开以前
    2020-12-31 06:35

    Since a socket solution has not yet been mentioned it is worth pointing out that sockets can be used as effective mutexes. Socket creation is an atomic operation, like mkdir is as Gunstick pointed out, so a socket is suitable to use as a lock or mutex.

    Tim Kay's Perl script 'Solo' is a very small and effective script to make sure only one copy of a script can be run at any one time. It was designed specifically for use with cron jobs, although it works perfectly for other tasks as well and I've used it for non-crob jobs very effectively.

    Solo has one advantage over the other techniques mentioned so far in that the check is done outside of the script you only want to run one copy of. If the script is already running then a second instance of that script will never even be started. This is as opposed to isolating a block of code inside the script which is protected by a lock. EDIT: If flock is used in a cron job, rather than from inside a script, then you can also use that to prevent a second instance of the script from starting - see example below.

    Here's an example of how you might use it with cron:

    */5 * * * * solo -port=3801 /path/to/script.sh args args args
    
    # "/path/to/script.sh args args args" is only called if no other instance of
    # "/path/to/script.sh" is running, or more accurately if the socket on port 3801
    # is not open. Distinct port numbers can be used for different programs so that
    # if script_1.sh is running it does not prevent script_2.sh from starting, I've
    # used the port range 3801 to 3810 without conflicts. For Linux non-root users 
    # the valid port range is 1024 to 65535 (0 to 1023 are reserved for root).
    
    * * * * * solo -port=3802 /path/to/script_1.sh
    * * * * * solo -port=3803 /path/to/script_2.sh
    
    # Flock can also be used in cron jobs with a distinct lock path for different
    # programs, in the example below script_3.sh will only be started if the one
    # started a minute earlier has already finished.
    
    * * * * * flock -n /tmp/path.to.lock -c /path/to/script_3.sh
    

    Links:

    • Solo web page: http://timkay.com/solo/
    • Solo script: http://timkay.com/solo/solo

    Hope this helps.

提交回复
热议问题