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
$

更新於:2019年7月30日

2K+ 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告