【问题标题】:What happens to file descriptors in Python 3 when .close() fails?当 .close() 失败时,Python 3 中的文件描述符会发生什么?
【发布时间】:2012-11-18 21:59:51
【问题描述】:

当我通过strace 运行以下 Python 3 代码时,它表现出一些奇怪的行为(至少对我而言):

import os
import sys

if len(sys.argv) != 2:
    print('Usage: ecpy <filename>')
sys.exit(1)
try:
    print('my PID: %d' % os.getpid())
    with open(sys.argv[1], 'w') as fp:
        try:
            fp.write('Hello Stack Overflow!')
        except IOError as e:
            print('### before close')
            print(str(e))
            sys.stdout.flush()
except IOError as e:
    print('### after close')
    print(str(e))
    sys.stdout.flush()

print('### after exception block')
sys.stdout.flush()

由于 I/O 是缓冲的,如果您使用 /dev/full 运行此代码,它不会失败,直到 fpwith 块的末尾关闭。这并不奇怪。在Python 2.7.3rc2(在我的系统上)中,代码在实际关闭fp对应的文件描述符后运行异常处理程序:

write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
close(3)                                = 0
munmap(0x7f9de3f78000, 4096)            = 0
write(1, "### after close\n", 16)       = 16
write(1, "[Errno 28] No space left on devi"..., 35) = 35
write(1, "### after exception block\n", 26) = 26

但是,在 Python 3.2.3(在我的系统上)中,异常块运行后文件描述符仍处于打开状态:

write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
write(1, "### after close\n", 16)       = 16
write(1, "[Errno 28] No space left on devi"..., 35) = 35
write(1, "### after exception block\n", 26) = 26
...
write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
close(3)                                = 0

解释器尝试多次写入文件,但静默失败。 Python 什么时候真正调用close()?什么在调用它?这种行为似乎泄露了文件描述符。

【问题讨论】:

    标签: python io python-3.x resource-leak


    【解决方案1】:

    我冒昧地向 bugs.python.org 提交了一个问题,让我们拭目以待,看看它是否成功。

    http://bugs.python.org/issue16597

    编辑:看起来这是一个错误,很好!

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2021-05-08
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多