Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the singleton running of shell script seriously

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to properly implement the singleton operation of shell scripts. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

A seemingly feasible method

A very simple idea is that when a new script is executed, check if there are other instances of the current script running, and if so, exit directly.

RunCount=$ (ps-ef | grep test.sh | grep-v grep-c) if ["${runCount}"-ge 1] then echo-e "test.sh already running,num:$ {runCount}" exit 1; fi while true do echo "test.sh run" sleep 1 done

Here, the number of test.sh scripts currently running is obtained through ps. If it is greater than 1, it means there are already running scripts.

But if you run it, you will find that there is more than one program.

$. / test.sh test.sh already running,num:2

Are you surprised? Why is that? The reason is that a command execution in a shell script is equivalent to fork execution of a process, where a program is executed to find tesh.sh and grep, and there is another script that is currently running, so naturally there are two at a time.

Of course, you can change the judgment conditions here, for example, the quantity is greater than 2, but it is not very good after all.

File lock

In fact, you have already introduced this method in "how to get only one of your programs running at a time", but it was previously used to write CSync programs, while here it is used for shell scripts.

Let's review what kind of process this is:

Check if there is a lock file before running, and the process in the file is running

If there is and the program is running, there is already an instance running

Otherwise, if there is no instance, create a lock file and write to the process id

Delete the lock file when you exit

Explain the first, why it is important to make sure that the process in the lock file is running, because in some cases if the file is exited at run time without deleting the file, the new instance will never run.

#! / usr/bin/env bash LOCKFILE=/tmp/test.lock if [- e ${LOCKFILE}] & & kill-0 `cat ${LOCKFILE} `; then echo "$0 already running" exit fi # ensures that when exiting, the lock file is deleted trap "rm-f ${LOCKFILE}; exit" INT TERM EXIT # writes the current program process id to the lock file echo $$> ${LOCKFILE} # do what you need sleep 1000 # delete the lock file rm-f ${LOCKFILE}

We try to run one of them, and then the other window tries to run:

$. / test.sh. / test.sh already running

Because there is already an instance running, it is found that the new program cannot be run. When the old script is finished, the new one will be ready to run.

In fact, there are a few ingenious points:

Kill-0`cat\ ${LOCKFILE} `is used to detect whether the process exists to avoid the absence of the process, but the lock file is still there, causing the later script to fail to run.

Trap "rm-f\ ${LOCKFILE}; exit" INT TERM EXIT is used to ensure that the lock file is deleted when the script exits.

The rm-f {LOCKFILE} script finally needs to delete the lock file

Flock

When it comes to locking files, we have to mention the flock command. Without some of the previous clever handling, it is often difficult for us to delete the lock files we previously created, such as:

The script was interrupted unexpectedly and there was no time to delete it.

Multiple scripts compete, resulting in an exception. For example, there is a script running earlier, which determines that there is no lock file, and the next step is ready to create, but another script is created first, which will lead to an exception.

So we can consider using flock:

#! / usr/bin/env bash LOCK_FILE=/tmp/test.lock exec 99 > "$LOCK_FILE" flock-n 99 if ["$?"! = 0]; other things to be done by the then echo "$0 already running" exit 1 fi # script sleep 1024

Explain:

Exec 99 > "$LOCK_FILE" means to create a file descriptor 99, pointing to the lock file, and why 99 descriptors are also possible, just to conflict with file descriptors that may be opened in the current script (for example, conflict with 0mem1mem2).

Flock-n 99 attempts to lock the file descriptor so that atomicity is guaranteed by the operating system

Once flock fails, we can quit here.

Even if it is locked, when the script exits, it will be automatically released.

So this avoids the situation where the lock is not released.

Another approach

Looking at flock's man manual, we find that it has another example of doing this:

["${FLOCKER}"! = "$0"] & & exec env FLOCKER= "$0" flock-en "$0"$0" $@ "| |:

Just add the above line at the beginning of the script. For example:

#! / usr/bin/env bash ["${FLOCKER}"! = "$0"] & & exec env FLOCKER= "$0" flock-en "$0"$0"$@" | |: # other things to be done by the script sleep 1024

Explain this: if the ${FLOCKER} environment variable is not set, try to lock the script itself, and if the lock is successful, run the current script (and take the original parameters), otherwise exit silently.

Summary

The idea of singleton operation itself is very simple, that is, to detect whether an instance is currently running, and if so, exit, but how to judge here is not so easy.

Finally, summarize some of the information that should be mastered in this article:

$0 script name

$@ script parameters

$$current script process id

$? Result of the execution of the previous command

Descriptor 0 standard input

Descriptor 1 standard output

Descriptor 2 standard error

Redirect

This is the end of this article on "how to properly implement the singleton operation of shell scripts". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report