English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To control files and io, we should usefcntlmodule. It is basicallyfcntl()
andioctl()
An interface for Unix routines.
All methods in this module take an integer or io.IOBase file descriptor as their first parameter.
To use this module, we should use the import statement.
import fcntl
There are some modules in the fcntl module, which are-
This method is used to perform operations on a file using a file descriptor. The operation is determined byopDefinition. The third parameter is optional. It can be an integer type value or a string type value. When the parameter is of integer type, the return value will be Cfcntl()
The value called. If it is a string, it represents a binary structure. When this function fails, it will raise an IOError.
This method is the same as this method.fcntl()
, but in this case, the parameter handling is more complex. In the parameters, if a variable buffer is passed, its behavior will depend on mutate_flag. If it is true, the buffer can be variable, otherwise it will act as a read-only buffer.
This method is used to perform locking operations on a file using file_descriptor. On some systems, it can be usedfcntl()
This method simulates this method.
This method is used as a wrapper for locking calls. Pass the operation parameter to lock or unlock the file. There are different operation values.
LOCK_UN-Unlock File
LOCK_SH-Shared Lock
LOCK_EX-Exclusive Lock
import fcntl, os, time counter_file = 'my_counter.txt' if not os.path.exists(counter_file): counter_file = open('my_counter.txt', 'w') counter_file.write('0') # Store 0 as starting number counter_file.close() for i in range(15) counter_file = open('my_counter.txt', 'r+) fcntl.flock(counter_file.fileno(), fcntl.LOCK_EX) count = int(counter_file.readline()) + 1 counter_file.seek(0) counter_file.write(str(count)) counter_file.close() print('Process ID: ' + str(os.getpid()) + ', Count: ' + str(count)) time.sleep(0.2)
Output Result
$ python3 example.py Process ID: 12698, Count: 1 Process ID: 12698, Count: 2 Process ID: 12698, Count: 3 Process ID: 12698, Count: 4 Process ID: 12698, Count: 5 Process ID: 12698, Count: 6 Process ID: 12698, Count: 7 Process ID: 12698, Count: 8 Process ID: 12698, Count: 9 Process ID: 12698, Count: 10 Process ID: 12698, Count: 11 Process ID: 12698, Count: 12 Process ID: 12698, Count: 13 Process ID: 12698, Count: 14 Process ID: 12698, Count: 15 $ $ $ cat my_counter.txt 15 $