关闭的文件描述符出了什么问题?

4
在下面的示例代码中,我们打开一个文件描述符到sandbox.log,并将其作为stdout提供给子进程,然后关闭文件描述符,但是子进程仍然可以写入该文件。 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?

你看起来正在使用Python 2。请查看Popenclose_fds参数。出于这些原因,3.2中更改了默认设置。 - cdarke
1个回答

6
每个进程都有自己的文件描述符集。在一个程序中关闭一个fd不会影响另一个程序。这就是为什么每个程序可以使用相同的fd号码来表示stdin(0),stdout(1)和stderr(2),以及为什么shell脚本通常只需打开fd 3而无需检查它是否可用。
文件描述符会被子进程继承,除非您明确设置了close-on-exec标志以防止继承。默认情况下,如果没有该标志,子进程将获得父进程文件描述符的副本。

谢谢约翰。你的回答非常启发人心。 - chmod 777 j

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接