Python provides various functions and commands for using and working with the files in codes. For working with these files we need to define file descriptors.
This Python module performs file control and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines. All the functions used in this module take a file descriptor 'fd' as their first argument to know which file they need to handle in the code.
1. fcntl.flock(fd, operation)
This function performs the lock operation on file descriptor fd (file objects providing a fileno() method are accepted as well).
If the flock() fails, an OSError exception is raised.
2. fcntl.lockf(fd, cmd, len=0, start=0, whence=0)
This is essentially a wrapper around the fcntl() locking calls. fd is the file descriptor (file objects providing a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values:
i.) LOCK_UN – unlock
(This command unlocks the locked data items/files)
ii.) LOCK_SH – acquire a shared lock
(this is a shared locking command, it is also called the read lock because it is used for reading the data items only. Shared locks supports read integrity and also ensures that the data in not in the position of getting updated by any process during the read-only requests.)
iii.) LOCK_EX – acquire an exclusive lock
(With this command the data items are locked such that the process which locked the data item/ file can read them as well as write and update them also. In Exclusive locks the data item can be locked by one process only.)
When cmd is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB (LOCK_NB means non-blocking) to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system). On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing.
'len' is the number of bytes to lock.
'start' is the byte offset at which the lock starts, relative to 'whence'.
'whence' is as with io.IOBase.seek(), specifically take below mentioned numbers:
0 – relative to the start of the file (os.SEEK_SET)
1 – relative to the current buffer position (os.SEEK_CUR)
2 – relative to the end of the file (os.SEEK_END)
The default for start is 0, which means to start at the beginning of the file. The default for len is 0 which means to lock to the end of the file. The default for whence is also 0.
Comments