Shell implements the singleton pattern

Usage scenario: Several shell scripts share a local derby library, and it is necessary to ensure that only a single shell script occupies the database at the same time.

 

Method 1: Check if the process exists

 

#!/bin/bash  
ScriptName=`basename $0`  
#basename, returns the base file name of a string parameter  
#pidof -x, find out the process PID of the shell script script, list all the process PIDs  
if [ `pidof -x $ScriptName | wc -w` -gt 2 ]; then  
  echo "Instance is running!"  
  exit 0  
else  
  sleep 10 #execute the program   
be  

 

 Verify that a process with the same basename exists in the current thread

 

Advantages: After the shell exits, it can be quickly detected; no files are generated.

Disadvantages: only suitable for a single shell script, if multiple scripts are mutually exclusive, it will not work.

 

Method 2: flock lock file

flock is an advisory lock on the entire file. That is, if a process puts a lock on a file (inode), other processes can know about it. (Advisory locks are not enforced by processes.) Best of all, its first argument is a file descriptor, and the lock is automatically released when this file descriptor is closed. When the process terminates, all file descriptors are closed. Therefore, in many cases, you don't need to consider unlocking.

lockit () {
  exec 7<>.lock
# try to lock the file
  flock -n 7 || {
#Failed to acquire lock
    echo "Waiting for lock to release..."
#Permanently wait for the lock to be acquired
    flock 7
  }
#Get the lock successfully
}

 Advantages: Solve the problem of sharing resources between multiple shell scripts

 Disadvantage: When the thread that acquired the lock exits (including kill), it takes a period of time before flock succeeds.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326612509&siteId=291194637