Quick-and-dirty way to ensure only one instance of

2018-12-31 09:51发布

What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?

30条回答
笑指拈花
2楼-- · 2018-12-31 10:18

You need an atomic operation, like flock, else this will eventually fail.

But what to do if flock is not available. Well there is mkdir. That's an atomic operation too. Only one process will result in a successful mkdir, all others will fail.

So the code is:

if mkdir /var/lock/.myscript.exclusivelock
then
  # do stuff
  :
  rmdir /var/lock/.myscript.exclusivelock
fi

You need to take care of stale locks else aftr a crash your script will never run again.

查看更多
一个人的天荒地老
3楼-- · 2018-12-31 10:18

If flock's limitations, which have already been described elsewhere on this thread, aren't an issue for you, then this should work:

#!/bin/bash

{
    # exit if we are unable to obtain a lock; this would happen if 
    # the script is already running elsewhere
    # note: -x (exclusive) is the default
    flock -n 100 || exit

    # put commands to run here
    sleep 100
} 100>/tmp/myjob.lock 
查看更多
听够珍惜
4楼-- · 2018-12-31 10:21

Here's an implementation that uses a lockfile and echoes a PID into it. This serves as a protection if the process is killed before removing the pidfile:

LOCKFILE=/tmp/lock.txt
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "already running"
    exit
fi

# make sure the lockfile is removed when we exit and then claim it
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${LOCKFILE}

# do stuff
sleep 1000

rm -f ${LOCKFILE}

The trick here is the kill -0 which doesn't deliver any signal but just checks if a process with the given PID exists. Also the call to trap will ensure that the lockfile is removed even when your process is killed (except kill -9).

查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 10:21

Some unixes have lockfile which is very similar to the already mentioned flock.

From the manpage:

lockfile can be used to create one or more semaphore files. If lock- file can't create all the specified files (in the specified order), it waits sleeptime (defaults to 8) seconds and retries the last file that didn't succeed. You can specify the number of retries to do until failure is returned. If the number of retries is -1 (default, i.e., -r-1) lockfile will retry forever.

查看更多
只若初见
6楼-- · 2018-12-31 10:21

why dont we use something like

pgrep -f $cmd || $cmd
查看更多
忆尘夕之涩
7楼-- · 2018-12-31 10:22

There's a wrapper around the flock(2) system call called, unimaginatively, flock(1). This makes it relatively easy to reliably obtain exclusive locks without worrying about cleanup etc. There are examples on the man page as to how to use it in a shell script.

查看更多
登录 后发表回答