in industrial applications, some files from industrial equipment will be placed in the specified directory, as these files need to be reformatted before being processed by higher-level software. At this point the processing of the script is most likely to be multiple instances of simultaneous operation, so these instances need a certain synchronization, to avoid multiple instances of simultaneous operation of a file caused by data mismatches and other problems. File lock commands can help us implement this synchronization logic.
code is as follows |
copy code |
/> Cat > test26.sh #!/bin/sh #1. Here you need to confirm that the flock command exists. If [-Z $ (which flock)]; then echo "flock doesn ' t exist." exit 1 fi |
The-e option in the
#2. Flock indicates that the file is locked, and the-W option indicates that if the file is being locked now, the current flock command waits 20 seconds, and if it can lock the file, continue execution. Otherwise, exit the command.
#3. The file locked here is the/VAR/LOCK/LOCKFILE1,-C option indicates that, if the lock is successful, the command followed by a double quotation mark is specified and, if it is more than one command, separated by a semicolon.
#4. You can start the script at two terminals and then observe the output of the script and the contents of the Lockfile1 file.
code is as follows |
copy code |
flock-e-W 20/ Var/lock/lockfile1-c "Sleep 10;echo ' Date" | Cat >>/var/lock/lockfile1 " if [$-ne 0]; then     &N bsp; echo "Fail." exit 1 Else echo "Success." exit 0 fi ctrl+d |