Python使用文件鎖實現(xiàn)進程間同步功能【基于fcntl模塊】
本文實例講述了Python使用文件鎖實現(xiàn)進程間同步功能。分享給大家供大家參考,具體如下:
簡介
在實際應用中,會出現(xiàn)這種應用場景:希望shell下執(zhí)行的腳本對某些競爭資源提供保護,避免出現(xiàn)沖突。本文將通過fcntl模塊的文件整體上鎖機制來實現(xiàn)這種進程間同步功能。
fcntl系統(tǒng)函數(shù)介紹
Linux系統(tǒng)提供了文件整體上鎖(flock)和更細粒度的記錄上鎖(fcntl)功能,底層功能均可由fcntl函數(shù)實現(xiàn)。
首先來了解記錄上鎖。記錄上鎖是讀寫鎖的一種擴展類型,它可用于有親緣關系或無親緣關系的進程間共享某個文件的讀與寫。被鎖住的文件通過其描述字訪問,執(zhí)行上鎖操作的函數(shù)是fcntl。這種類型的鎖在內(nèi)核中維護,其宿主標識為fcntl調(diào)用進程的進程ID。這意味著這些鎖用于不同進程間的上鎖,而不是同一進程內(nèi)不同線程間的上鎖。
fcntl記錄上鎖即可用于讀也可用于寫,對于文件的任意字節(jié),最多只能存在一種類型的鎖(讀鎖或?qū)戞i)。而且,一個給定字節(jié)可以有多個讀寫鎖,但只能有一個寫入鎖。
對于一個打開著某個文件的給定進程來說,當它關閉該文件的任何一個描述字或者終止時,與該文件關聯(lián)的所有鎖都被刪除。鎖不能通過fork由子進程繼承。
NAME
fcntl - manipulate file descriptor
SYNOPSIS
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
DESCRIPTION
fcntl() performs one of the operations described below on the open file descriptor fd. The operation is determined by cmd.
fcntl() can take an optional third argument. Whether or not this argument is required is determined by cmd. The required argument type
is indicated in parentheses after each cmd name (in most cases, the required type is int, and we identify the argument using the name
arg), or void is specified if the argument is not required.
Advisory record locking
Linux implements traditional ("process-associated") UNIX record locks, as standardized by POSIX. For a Linux-specific alternative with
better semantics, see the discussion of open file description locks below.
F_SETLK, F_SETLKW, and F_GETLK are used to acquire, release, and test for the existence of record locks (also known as byte-range, file-
segment, or file-region locks). The third argument, lock, is a pointer to a structure that has at least the following fields (in
unspecified order).
struct flock {
...
short l_type; /* Type of lock: F_RDLCK,
F_WRLCK, F_UNLCK */
short l_whence; /* How to interpret l_start:
SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
pid_t l_pid; /* PID of process blocking our lock
(set by F_GETLK and F_OFD_GETLK) */
...
};
其次,文件上鎖源自Berkeley的Unix實現(xiàn)支持給整個文件上鎖或解鎖的文件上鎖(file locking),但沒有給文件內(nèi)的字節(jié)范圍上鎖或解鎖的能力。
fcntl模塊及基于文件鎖的同步功能。
Python fcntl模塊提供了基于文件描述符的文件和I/O控制功能。它是Unix系統(tǒng)調(diào)用fcntl()和ioctl()的接口。因此,我們可以基于文件鎖來提供進程同步的功能。
import fcntl
class Lock(object):
def __init__(self, file_name):
self.file_name = file_name
self.handle = open(file_name, 'w')
def lock(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
def unlock(self):
fcntl.flock(self.handle, fcntl.LOCK_UN)
def __del__(self):
try:
self.handle.close()
except:
pass
應用
我們做一個簡單的場景應用:需要從指定的服務器上下載軟件版本到/exports/images目錄下,因為這個腳本可以在多用戶環(huán)境執(zhí)行。我們不希望下載出現(xiàn)沖突,并僅在該目錄下保留一份指定的軟件版本。下面是基于文件鎖的參考實現(xiàn):
if __name__ == "__main__":
parser = OptionParser()
group = OptionGroup(parser, "FTP download tool", "Download build from ftp server")
group.add_option("--server", type="string", help="FTP server's IP address")
group.add_option("--username", type="string", help="User name")
group.add_option("--password", type="string", help="User's password")
group.add_option("--buildpath", type="string", help="Build path in the ftp server")
group.add_option("--buildname", type="string", help="Build name to be downloaded")
parser.add_option_group(group)
(options, args) = parser.parse_args()
local_dir = "/exports/images"
lock_file = "/var/tmp/flock.txt"
flock = Lock(lock_file)
flock.lock()
if os.path.isfile(os.path.join(local_dir, options.buildname)):
log.info("build exists, nothing needs to be done")
log.info("Download completed")
flock.unlock()
exit(0)
log.info("start to download build " + options.buildname)
t = paramiko.Transport((options.server, 22))
t.connect(username=options.username, password=options.password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(os.path.join(options.buildpath, options.buildname),
os.path.join(local_dir, options.buildname))
sftp.close()
t.close()
log.info("Download completed")
flock.unlock()
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結(jié)》、《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python中functools.lru_cache的具體使用
本文主要介紹了python中functools.lru_cache的具體使用,通過functools.lru_cache,你可以輕松優(yōu)化具有重復計算的函數(shù),大大提高代碼的執(zhí)行效率2024-09-09
Python中使用Minio實現(xiàn)圖像或視頻文件存儲的步驟
本文章向大家介紹了Minio這一款簡易的云存儲服務器,并講述了如何在Python中去使用Minio,實現(xiàn)了視頻文件的上傳和獲取,感興趣的朋友一起看看吧2025-02-02
從零開始學習Python與BeautifulSoup網(wǎng)頁數(shù)據(jù)抓取
想要從零開始學習Python和BeautifulSoup網(wǎng)頁數(shù)據(jù)抓?。勘局改蠈槟闾峁┖唵我锥闹笇?讓你掌握這兩個強大的工具,不管你是初學者還是有經(jīng)驗的開發(fā)者,本指南都能幫助你快速入門并提升技能,不要錯過這個機會,開始你的編程之旅吧!2024-01-01
Python使用jsonpath-rw模塊處理Json對象操作示例
這篇文章主要介紹了Python使用jsonpath-rw模塊處理Json對象操作,結(jié)合實例形式分析了Python使用requests與response處理json的方法,并給出了jsonpath_rw模塊操作json對象的基本示例,需要的朋友可以參考下2018-07-07
python使用numpy按一定格式讀取bin文件的實現(xiàn)
這篇文章主要介紹了python使用numpy按一定格式讀取bin文件的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

