For example, to require scripts to only access a certain resource in sequence, such as disk files, you can refer to the following implementation.
Copy codeThe Code is 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.
#
#/Path/to/lock/. note; directory, not a file.
# Shocould 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]
Do
Rm lock. $
Read pid>/dev/null 2> & 1 <lock. pid
If [-n "$ pid"]; then
If [-e/proc/$ pid]; then
Cd $ oldpath
Return 1 # Lock is 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 back to 'wait' loop
#11 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 is 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; do
While! Getlock; do
# 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 multiple execution of scripts (1)Copy codeThe Code is as follows: while ['ps x | grep-v grep | grep filename. sh | wc-l'-gt 0];
Do
Exit
Done
Put the content at the top of the script
Replace filename. sh with the name of the script to be monitored.
Another method is to synchronize the dead Loop Based on different environments and script content. The method is easy to write later.