侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python使用文件锁实现进程间同步功能【基于fcntl模块】

Python  /  管理员 发布于 7年前   182

本文实例讲述了Python使用文件锁实现进程间同步功能。分享给大家供大家参考,具体如下:

简介

在实际应用中,会出现这种应用场景:希望shell下执行的脚本对某些竞争资源提供保护,避免出现冲突。本文将通过fcntl模块的文件整体上锁机制来实现这种进程间同步功能。

fcntl系统函数介绍

Linux系统提供了文件整体上锁(flock)和更细粒度的记录上锁(fcntl)功能,底层功能均可由fcntl函数实现。

首先来了解记录上锁。记录上锁是读写锁的一种扩展类型,它可用于有亲缘关系或无亲缘关系的进程间共享某个文件的读与写。被锁住的文件通过其描述字访问,执行上锁操作的函数是fcntl。这种类型的锁在内核中维护,其宿主标识为fcntl调用进程的进程ID。这意味着这些锁用于不同进程间的上锁,而不是同一进程内不同线程间的上锁。

fcntl记录上锁即可用于读也可用于写,对于文件的任意字节,最多只能存在一种类型的锁(读锁或写锁)。而且,一个给定字节可以有多个读写锁,但只能有一个写入锁。

对于一个打开着某个文件的给定进程来说,当它关闭该文件的任何一个描述字或者终止时,与该文件关联的所有锁都被删除。锁不能通过fork由子进程继承。

NAME    fcntl - manipulate file descriptorSYNOPSIS    #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 fcntlclass 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相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Python实现扩展内置类型的方法分析
    下一条:
    python利用paramiko连接远程服务器执行命令的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客