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


Posted in Python onOctober 16, 2017

本文实例讲述了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程序设计有所帮助。

Python 相关文章推荐
Python高级应用实例对比:高效计算大文件中的最长行的长度
Jun 08 Python
Python去除列表中重复元素的方法
Mar 20 Python
Python+django实现文件下载
Jan 17 Python
打包发布Python模块的方法详解
Sep 18 Python
python xpath获取页面注释的方法
Jan 14 Python
WIn10+Anaconda环境下安装PyTorch(避坑指南)
Jan 30 Python
python rsa实现数据加密和解密、签名加密和验签功能
Sep 18 Python
python Tensor和Array对比分析
Jan 08 Python
Python3+Selenium+Chrome实现自动填写WPS表单
Feb 12 Python
python图片剪裁代码(图片按四个点坐标剪裁)
Mar 10 Python
Python使用xpath实现图片爬取
Sep 16 Python
python操作xlsx格式文件并读取
Jun 02 Python
python利用paramiko连接远程服务器执行命令的方法
Oct 16 #Python
基于使用paramiko执行远程linux主机命令(详解)
Oct 16 #Python
python中文件变化监控示例(watchdog)
Oct 16 #Python
python中import reload __import__的区别详解
Oct 16 #Python
使用Python操作excel文件的实例代码
Oct 15 #Python
python出现&quot;IndentationError: unexpected indent&quot;错误解决办法
Oct 15 #Python
python 二分查找和快速排序实例详解
Oct 13 #Python
You might like
PHP中的strtr函数使用介绍(str_replace)
2011/10/20 PHP
php操作SVN版本服务器类代码
2011/11/27 PHP
关于PHP通用返回值设置方法
2017/03/31 PHP
ThinkPHP实现分页功能
2017/04/28 PHP
PHP实现的简单异常处理类示例
2017/05/04 PHP
laravel 5.3 单用户登录简单实现方法
2019/10/14 PHP
JavaScript 自动分号插入(JavaScript synat:auto semicolon insertion)
2009/11/04 Javascript
浏览器常用高宽的jquery插件
2011/02/24 Javascript
js对图片base64编码字符串进行解码并输出图像示例
2014/03/17 Javascript
javascript框架设计读书笔记之模块加载系统
2014/12/02 Javascript
利用Angularjs和bootstrap实现购物车功能
2016/08/31 Javascript
利用Javascript开发一个二维周视图日历
2017/12/14 Javascript
vue拖拽排序插件vuedraggable使用方法详解
2020/08/21 Javascript
详解ES6实现类的私有变量的几种写法
2021/02/10 Javascript
[55:16]Mski vs VGJ.S Supermajor小组赛C组 BO3 第二场 6.3
2018/06/04 DOTA
使用Python简单的实现树莓派的WEB控制
2016/02/18 Python
python的多重继承的理解
2017/08/06 Python
Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法
2018/03/13 Python
Python下调用Linux的Shell命令的方法
2018/06/12 Python
Python符号计算之实现函数极限的方法
2019/07/15 Python
Python tensorflow实现mnist手写数字识别示例【非卷积与卷积实现】
2019/12/19 Python
浅谈python出错时traceback的解读
2020/07/15 Python
Python调用SMTP服务自动发送Email的实现步骤
2021/02/07 Python
HTML5实现分享到微信好友朋友圈QQ好友QQ空间微博二维码功能
2018/01/03 HTML / CSS
印度网上购物首选目的地:Flipkart
2016/08/01 全球购物
波比布朗英国官网:Bobbi Brown英国
2017/11/13 全球购物
戴尔新加坡官网:Dell Singapore
2020/12/13 全球购物
大学生毕业自我鉴定范文
2013/11/03 职场文书
优秀毕业自我鉴定
2014/02/15 职场文书
幼儿园庆六一活动方案
2014/03/06 职场文书
企业形象策划方案
2014/05/29 职场文书
焦点访谈观后感
2015/06/11 职场文书
求职信如何撰写?
2019/05/22 职场文书
vue-cli3.0修改打包后的文件名和文件地址,打包后本地运行报错解决
2022/04/06 Vue.js
Python数据可视化之Seaborn的安装及使用
2022/04/19 Python
Golang Elasticsearches 批量修改查询及发送MQ
2022/04/19 Golang