Python 中的 fcntl 和 ioctl 系统调用
要控制文件和 I/O,我们应该使用fcntl模块。它基本上是 fcntl() 和 ioctl() Unix例程的一个接口。
此模块中的所有方法都将一个整数或 io.IOBase 文件描述符作为其第一个参数。
要使用此模块,我们应该使用以下方法导入它。
import fcntl
fcntl 模块有一些方法,它们是:
方法 fcntl.fcntl(fd, op[, arg])
此方法用于使用文件描述符对文件执行操作。操作由op定义。第三个参数是可选的。它可以是整数类型值或字符串类型值。当参数为整数类型时,返回值将是 C fcntl() 调用的值。当它是字符串时,它表示二进制结构。当此函数失败时,它会引发 IOError。
方法 fcntl.ioctl(fd, op[, arg[, mutate_flag]])
此方法与 fcntl() 方法相同,但在这种情况下,参数处理更复杂。在参数中,如果传递了可变缓冲区,则其行为将取决于 mutate_flag。当它为真时,缓冲区可以是可变的,否则它将像只读缓冲区一样工作。
方法 fcntl.flock(fd, op)
此方法用于使用文件描述符对文件执行锁定操作 op。在某些系统上,此方法可以使用 fcntl() 方法进行模拟。
方法 fcntl.lockf(fd, operation[, length[, start[, whence]]])
此方法用作锁定调用的包装器。操作参数用于锁定或解锁文件。操作有不同的值。
LOCK_UN - 解锁文件
LOCK_SH - 共享锁
LOCK_EX - 排他锁
示例代码
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)
输出
$ 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 $
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP