python - 关闭的文件描述符是怎么回事?

标签 python unix file-descriptor python-os

在下面的示例代码中,我们打开一个文件描述符到 sandbox.log,将其作为标准输出提供给子进程,然后关闭文件描述符,但子进程仍然可以写入文件。 subprocess.Popen 是否在内部复制文件描述符?将文件描述符传递给子进程后关闭文件描述符是否安全?

import subprocess
import os
import time


print 'create or clear sandbox.log'
subprocess.call('touch sandbox.log', shell=True)
subprocess.call('echo "" > sandbox.log', shell=True)

print 'open the file descriptor'
fd = os.open('sandbox.log', os.O_WRONLY)

command = 'sleep 10 && echo "hello world"'
print 'run the command'
p = subprocess.Popen(command, stdout=fd, stderr=subprocess.STDOUT, shell=True)

os.close(fd)

try:
    os.close(fd)
except OSError:
    print 'fd is already closed'
else:
    print 'fd takes some time to close'

if p.poll() is None:
    print 'p isnt finished, but fd is closed'

p.wait()
print 'p just finished'

with open('sandbox.log') as f:
    if any('hello world' in line for line in f):
        raise Exception("There's text in sandbox.log. Whats going on?")

作为引用,我将上述代码作为脚本运行得到以下输出:

% python test_close_fd.py
create or clear sandbox.log
open the file descriptor
run the command
fd is already closed
p isnt finished, but fd is closed
p just finished
Traceback (most recent call last):
  File "test_close_fd.py", line 34, in <module>
    raise Exception("There's text in sandbox.log. Whats going on?")
Exception: There's text in sandbox.log. Whats going on?

最佳答案

每个进程都有自己的一组文件描述符。在一个程序中关闭一个 fd 不会影响另一个程序。这就是为什么每个程序都可以对 stdin (0)、stdout (1) 和 stderr (2) 使用相同的 fd 编号,以及为什么 shell 脚本通常可以直接打开 fd 3 而无需检查它是否可用。

文件描述符由子进程继承,除非您通过设置 close-on-exec 标志明确阻止它。默认情况下,如果没有该标志,子进程将获取父进程的文件描述符的副本。

关于python - 关闭的文件描述符是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713514/

相关文章:

python - 线程 :must be a sequence, 中的异常不是实例

python - Roc 曲线和截止点。 Python

python - Django startproject 的问题

Python itertools.product 构建总和并添加到新列表

c# - .NET Core - 目录权限 Linux

c - 逐行读取文件并在c中进行比较

mysql - 如何将登录参数传递给mysql

c - 使用 fdopen 时文件描述符错误?

c - 关闭标准输出后打开的文件的 POSIX 定义缓冲是什么?

c - 我如何从单个文件描述符分配多个 MMAP?