Python使用文件锁实现进程间同步功能【基于fcntl模块】
作者:Think-througher 发布时间:2022-07-04 17:45:15
本文实例讲述了Python使用文件锁实现进程间同步功能。分享给大家供大家参考,具体如下:
简介
在实际应用中,会出现这种应用场景:希望shell下执行的脚本对某些竞争资源提供保护,避免出现冲突。本文将通过fcntl模块的文件整体上锁机制来实现这种进程间同步功能。
fcntl系统函数介绍
Linux系统提供了文件整体上锁(flock)和更细粒度的记录上锁(fcntl)功能,底层功能均可由fcntl函数实现。
首先来了解记录上锁。记录上锁是读写锁的一种扩展类型,它可用于有亲缘关系或无亲缘关系的进程间共享某个文件的读与写。被锁住的文件通过其描述字访问,执行上锁操作的函数是fcntl。这种类型的锁在内核中维护,其宿主标识为fcntl调用进程的进程ID。这意味着这些锁用于不同进程间的上锁,而不是同一进程内不同线程间的上锁。
fcntl记录上锁即可用于读也可用于写,对于文件的任意字节,最多只能存在一种类型的锁(读锁或写锁)。而且,一个给定字节可以有多个读写锁,但只能有一个写入锁。
对于一个打开着某个文件的给定进程来说,当它关闭该文件的任何一个描述字或者终止时,与该文件关联的所有锁都被删除。锁不能通过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实现支持给整个文件上锁或解锁的文件上锁(file locking),但没有给文件内的字节范围上锁或解锁的能力。
fcntl模块及基于文件锁的同步功能。
Python fcntl模块提供了基于文件描述符的文件和I/O控制功能。它是Unix系统调用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目录下,因为这个脚本可以在多用户环境执行。我们不希望下载出现冲突,并仅在该目录下保留一份指定的软件版本。下面是基于文件锁的参考实现:
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程序设计有所帮助。
来源:http://blog.csdn.net/jinguangliu/article/details/71773784


猜你喜欢
- 背景写一个python脚本,实现简单的http服务器功能:1.浏览器中输入网站地址:172.20.52.163:200142.server接
- PHP生成桌面快捷方式就是这么的简单,大家生成的时候改下你要生成的网站即可。dianji.html代码:<a href="a
- 一、为什么需要虚拟环境?这里的环境,指的就是 Python 代码的运行环境。它应该包含以下信息:Python 解释器,用哪个解释器来执行代码
- 准备正常情况下,创建class的实例后,可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。首先定义一个classclass A(obj
- v1.0.0完成基础框架、初始功能背景:为了提高日常工作效率、学习界面工具开发,可以将一些常用的功能集成到一个小的测试工具中,供大家使用。一
- select 终极美化,主要是针对下拉框的美化一个很古老的话题了,不过貌似目前为止也没有比较好的做到,在jxdawei的基础上做了
- 什么是循环呢?简单理解,循环就是反复的去做某一件事情。生活中的例子:比如我们听歌的时候,在歌曲的页面就会出现单曲循环、列表循环、随机播放以及
- PyQt5中信号与槽可以说是对事件处理机制的高级封装,如果说事件是用来创建窗口控件的,那么信号与槽就是用来对这个控件进行使用的,比如一个按钮
- 我在配置mysql时将配置文件中的默认存储引擎设定为了InnoDB。今天查看了MyISAM与InnoDB的区别,在该文中的第七条“MyISA
- 主要是运用java.util.regex类。 import java.util.regex.Matcher;import java
- <%''调用例子'Dim int_RPP,int_Start,int_showNumberLink
- time()方法返回时间,在UTC时代以秒表示浮点数。注意:尽管在时间总是返回作为一个浮点数,并不是所有的系统提供时间超过1秒精
- 将数据插入到MySQL表,需要使用SQL INSERT INTO命令。可以将数据插入到MySQL表使用mysql>提示符下或使用任何脚
- 下面这段代码是asp编写的用来识别客户端是否为手机浏览器,以及手机类型的代码。主要用于手机网站的建设,以便实现相同网址下的不同版本网站(比如
- 本文实例讲述了python执行等待程序直到第二天零点的方法。分享给大家供大家参考。具体分析如下:如果需要通过python每天凌晨定时执行执行
- python中return的用法1、return语句就是把执行结果返回到调用的地方,并把程序的控制权一起返回程序运行到所遇到的第一个retu
- PHP PDO预定义常量以下常量由本扩展模块定义,因此只有在本扩展的模块被编译到PHP中,或者在运行时被动态加载后才有效。注意:PDO使用类
- 前言今天我们简单说下Python函数和控制语句,大纲如下:函数“脏活累活交给函数来做”,首先,看看P
- 本文实例讲述了Python3.5内置模块之os模块、sys模块、shutil模块用法。分享给大家供大家参考,具体如下:1、os模块:提供对操
- php中主要用到的就是要用到fread()和fwirte()。而静态页面生成了之后,就会牵扯到修改的问题。这里可以用到正则匹配的方法来替换模