python multiprocessing 文件句柄继承问题

由于Python 解析器的GIL 问题,多线程的效率并不理想。于是 python 提供了 multiprocessing 模块让你向创建线程一样创建进程,非常方便。但是也有一个问题,那就是如果父进程打开文件,在创建子进程前没有关闭,那么子进程也会占用这个文件,即使在子进程中关闭也无用。

testFile = None

def empty_process(queue, fileno):
    if testFile:
        testFile.close()
        print "run under linux"
    else:
        print "run under win32"
    try:
        os.close(fileno)
    except:
        traceback.print_exc()
    queue.put('OK')

def test_process1():
    queue = multiprocessing.Queue()
    testFile = open('a.txt','a+')

    p = Process(target=empty_process, args=(queue, testFile.fileno() ))
    p.start()

    print queue.get()
    try:
        testFile.close()
        os.unlink('a.txt')
    except:
        traceback.print_exc()
    p.join()




上面这段代码,os.unlink('a.txt') 一定会失败,在子进程中无法关闭testFile。


在网上搜索了好长时间终于找到办法了。


def test_process2():
    queue = multiprocessing.Queue()
    testFile = open('a.txt','a+')

    if sys.platform == "win32":
        win32api.SetHandleInformation(
            msvcrt.get_osfhandle(testFile.fileno()),
            win32con.HANDLE_FLAG_INHERIT,
            0)

    p = Process(target=empty_process, args=(queue, testFile.fileno() ))
    p.start()

    print queue.get()
    try:
        testFile.close()
        os.unlink('a.txt')
    except:
        traceback.print_exc()
    p.join()

windows上通过 SetHandleInformation 解决。linux还没有研究过,等下回有空研究研究。



 

转载于:https://my.oschina.net/tc1980/blog/76170

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值