The Linux shell command file locking function

Source: Internet
Author: User
Tags flock

      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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.