For example, you might want to refer to the following implementation for a script that requires only sequential access to a resource, such as a disk file.
Copy Code code as follows:
#!/bin/bash
#
# File locking using Bash.
# ver 0.1.6
#
# Author:malundao (malundao@sina.com)
# date:2011-08-31
# ref:http://unix.derkeiler.com/newsgroups/comp.unix.shell/2005-09/0472.html
#
# Note:
# Shflock_cleanhook () is a user defined function to clean up user-specific sth.
#
#/path/to/lock/. Note directory, not a file.
# should be modified
Lockpath= "/tmp"
Cleanup () {
Shflock_cleanhook
CD $LOCKPATH
[e Lock.pid] | | Exit
Read PID >/dev/null 2>&1 <lock.pid
If [-N "$pid"]; Then
If ["$pid" = = "$$"]; Then
Rm-f lock. $pid
Rm-f Lock.pid
Exit
Fi
Fi
Exit
}
# trap EXIT?
Trap ' cleanup ' HUP INT TERM
Getlock () {
Oldpath= ' pwd '
CD $LOCKPATH
While
echo $$ > lock.$$
[-E Lock.pid]
Todo
RM lock.$$
Read PID >/dev/null 2>&1 <lock.pid
If [-N "$pid"]; Then
If [-e/proc/$pid]; Then
CD $oldpath
Return 1 # Lock's taken by others
Else
#unsafe: Rm-f lock. $pid
echo warn:please Delete stale lock.pid by HAND.
Return 2
Fi
Else
# Sleep some seconds,then ' while ' Loop
# One is a prime number, $$ as a random.
Echo Sleep $ (($$% 11))
Sleep $ (($$% 11))
Fi
Done
# ' Ln-s ' is an atom op.
Ln-s lock.$$ lock.pid >/dev/null 2>&1
If [$?-eq 0]; Then
CD $oldpath
Return 0 # We got the lock
Else
[e Lock.pid] | | echo warn:please Delete Hanging lock.pid by HAND.
CD $oldpath
Return 3 # Lock's probably taken by others.
Fi
}
Putlock () {
Oldpath= ' pwd '
CD $LOCKPATH && rm-f lock.$$ lock.pid
CD $oldpath
}
# # Test
Shflock_cleanhook () {
Echo I\ ' m a hook.
}
While true; Todo
While! Getlock; Todo
#echo Wait a second ...
Sleep 1
Done
echo \[$$\] ' date ', now hold lock for 3 seconds ...
Sleep 3
#echo Putlock
Putlock
Sleep 1 # Yield
Done
Prevent scripts from executing multiple times (i)
Copy Code code as follows:
While [' PS x |grep-v grep|grep filename.sh|wc-l '-gt 0];
Todo
Exit
Done
Put the content on top of the script
filename.sh Replace the name of the script you want to monitor
Another way is to die loops can be based on different environments, different script content, the method used is also synchronized, the method is very simple later in writing