python USES fcntl module to implement program locking function example

  • 2020-06-07 04:46:06
  • OfStack

This article shows that python USES fcntl module to realize program locking function. To share for your reference, specific as follows:

The fcntl module for locking files was introduced in python


import fcntl

Open 1 file


## Current directory test The file must exist first. If it does not exist, an error will be reported. Or open it as write 
f = open('./test')

Encrypt the file:


fcntl.flock(f,fcntl.LOCK_EX)

This locks the test file. If another process locks the test file, it will not succeed and will block, but will not exit the program.

Unlock: fcntl.flock(f,fcntl.LOCK_UN)

fcntl module:

flock() : flock(f, operation)

operation: Including:
fcntl. LOCK_UN unlocked
fcntl LOCK_EX exclusive lock
fcntl. LOCK_SH Shared lock
fcntl.LOCK_NB non-blocking lock

LOCK_SH Shared lock: All processes do not have write access, even locked ones. All processes have read access.

LOCK_EX Exclusive lock: Processes other than the locked process do not have read or write access to the locked file.
LOCK_NB Non-blocking lock:
If this parameter is specified, the function returns immediately if it cannot obtain the file lock, otherwise it waits to obtain the file lock.

LOCK_NB can be bitwise or (|) with LOCK_SH or LOCK_NB. fcnt.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB)

See example:


import sys
import time
import fcntl
class FLOCK(object):
 def __init__(self, name):
  self.fobj = open(name, 'w')
  self.fd = self.fobj.fileno()
 def lock(self):
  try:
   fcntl.lockf(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) #  Lock the file, use it fcntl.LOCK_NB
   print ' Lock the file. Hold on  ... ...'
   time.sleep(20)
   return True
  except:
   print ' The file is locked and cannot be executed. Please run later. '
   return False
def unlock(self):
 self.fobj.close()
 print ' Are unlocked '
if __name__ == "__main__":
 print sys.argv[1]
 locker = FLOCK(sys.argv[1])
 a = locker.lock()
 if a:
  print ' The file is locked '
 else:
  print ' Unable to execute, program locked, please wait '

First run 1 terminal to print:

python lockfile. py test
test
Lock the file, hold on... .
The file is locked

Run another terminal:

test
The file is locked and cannot be executed. Please run later.
Unable to execute, program locked, please wait

For more information about Python, please refer to: Python Encryption and Decryption algorithms and techniques summary, Python Coding skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Using Techniques Summary, Python String Manipulation Techniques Summary and Python Introduction and Advanced Classic Tutorial

I hope this article has been helpful in Python programming.


Related articles: