fcntl locking module


#
!/usr/bin/python # coding:utf8 Import OS Import SYS Import Time Import the fcntl # Import module class FLOCK(object): def __init__(self, name): """ : Param name: the file 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_NB: used fcntl.LOCK_NB, the process has already locked the file, exit when not lock this process is not blocked. If not non-blocking parameters, the lock is not stuck in here has just wait until I got the lock Print ( ' locked to the document, wait ... ... ' ) the time.sleep ( 20 ) return True the except Exception AS E: Print ( ' file locking can not be performed, please try to run \ the n-. ' , E) return False def unlock(self): self.fobj.close() Print ( ' unlocked ' ) if __name__ == "__main__": locker = FLOCK(sys.argv[1]) A = locker.lock () IF A: Print ( ' file is locked ' ) the else : Print ( ' can not be executed, the program is locked, please wait ' )

The difference fcntl.flock and fcntl.lockf: http: //blog.chinaunix.net/uid-28541347-id-5678998.html

https://blog.csdn.net/mydriverc2/article/details/80263930

lockf child process does not inherit the main process lock

flock child processes inherit the lock of the main process, this feeling with some more

1. flock function prototype in linux

#include 

int flock(int fd, int operation);  // Apply or remove an advisory lock on the open file specified by fd,只是建议性锁

    Where fd is the file descriptor returned by the system call open, operation options are:

LOCK_SH: shared lock

LOCK_EX: exclusive lock or exclusive lock

LOCK_UN: Unlock.

LOCK_NB: non-blocking (for use with the above three operations)

    About flock function, you must first know the flock function can only lock the entire file, but can not be locked to a particular portion of the file, which is the first important distinction to fcntl / lockf, and an area on the latter may file lock. Secondly, Flock can only produce hortatory lock. We know that there is a mandatory lock (mandatory lock) and advised lock (advisory lock) linux. The so-called mandatory locks, is better understood, is that the lock on your door, the most terrible is only one key, only one process can operate. The so-called lock advice, is essentially an agreement, before you access a file, check the locks, which lock when its role was, if you were not so kind, willy-nilly, it is necessary to read and write, then the lock does not have any advice effect. And abide by the agreement, the process of reading and writing that check before lock, called the cooperation process. Again, the difference between flock and fcntl / lockf mainly in the fork and dup.

    (1) lock flock is created and file open entry (struct file) associated, rather than fd. This means that after copying files fd (by fork or dup), then through the two fd can operate the lock (fd for example, by a lock, the lock can be released by another fd), that is child inherits lock the parent process. But locked off during one fd, the lock will not release (as file structure and not released), only when all the copy out fd, the lock will be released.

 

#!/usr/bin/env python
# -*- coding:utf8 -*-

Import OS
 Import SYS
 Import Time
 Import the fcntl   # Import module

class FLOCK(object):
    def __init__(self, name):
        """ 
        : Param name: the file name
        """
        self.fobj = open(name, 'w')
        self.fd = self.fobj.fileno()

    def lock(self):
        try:
            fcntl.flock (self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)   # LOCK_NB: used fcntl.LOCK_NB, the process has already locked the file, exit when not lock this process does not block if not Non-blocking parameters, not here on the card lock> 
has been waiting to get the lock             Print ( ' has been locked to the document, ... ... ' )
            fork_resu = os.fork ()
             IF fork_resu == 0:
                 Print ( ' the child sleep ' )
                the time.sleep ( 20 )
                 Print ( ' child process exits ' )
             the else :
                sys.exit ( ' primary process has exited ' )
            the time.sleep ( 20 )
             # return True 
        the except Exception AS E: 
             Print ( ' file is locked, can not be performed, please try to run \ the n-. ' , E)
             return False
             return False


    def unlock(self):
        self.fobj.close()
        Print ( ' unlocked ' )


if __name__ == "__main__":
    locker = FLOCK(sys.argv[1])
    locker.lock()
flock child inherits lock codes
'' ' Window to run 1
[root@vm192-168-3-2 fcn_study]# python locktest.py  l.txt
Has been locked to the document, ... ...
Primary process has exited
The child sleep
(base) [root@vm192-168-3-2 fcn_study]# 
'' ' 
' '' Window run 2
[root@vm192-168-3-2 fcn_study]# python locktest.py  l.txt
File is locked, you can not do this, please run later.
 [Errno 11] Resource temporarily unavailable

'''

If the code is changed to lock lockf

'' ' Window 1
python locktest.py  l.txt
Has been locked to the document, ... ...
Primary process has exited
(Base) [root @ vm192-168-3-2 fcn_study] # the child sleep

'' ' 
' '' Window 2
root@vm192-168-3-2 fcn_study]# python locktest.py  l.txt
Has been locked to the document, ... ...
Primary process has exited
(Base) [root @ vm192-168-3-2 fcn_study] # the child sleep



---- Window 1 and 2 had no effect on each other
'''

 

Guess you like

Origin www.cnblogs.com/zhangmingda/p/11767787.html