栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

检查文件是否未打开或未被其他进程使用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

检查文件是否未打开或未被其他进程使用

试图找出文件是否正在被另一个进程使用的问题是竞争条件的可能性。您可以检查一个文件,确定它未被使用,然后在打开它之前,另一个进程(或线程)会跳入并抓住它(甚至删除它)。

好的,假设您决定忍受这种可能性,并希望不会发生。检查其他进程正在使用的文件取决于操作系统。

在Linux上,这很简单,只需遍历/ proc中的PID。这是一个生成器,用于迭代用于特定PID的文件:

def iterate_fds(pid):    dir = '/proc/'+str(pid)+'/fd'    if not os.access(dir,os.R_OK|os.X_OK): return    for fds in os.listdir(dir):        for fd in fds: full_name = os.path.join(dir, fd) try:     file = os.readlink(full_name)     if file == '/dev/null' or        re.match(r'pipe:[d+]',file) or        re.match(r'socket:[d+]',file):         file = None except OSError as err:     if err.errno == 2:   file = None     else:         raise(err) yield (fd,file)

在Windows上,它不是那么简单,API尚未发布。有一个

handle.exe
可以使用的sysinternals工具(),但我建议使用PyPi模块
psutil
,该模块是可移植的(即,它也可以在Linux上运行,并且可能在其他OS上运行):

import psutilfor proc in psutil.process_iter():    try:        # this returns the list of opened files by the current process        flist = proc.open_files()        if flist: print(proc.pid,proc.name) for nt in flist:     print("t",nt.path)    # This catches a race condition where a process ends    # before we can examine its files        except psutil.NoSuchProcess as err:        print("****",err)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646997.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号