python中什么是文件描述符_python – 关闭文件描述符会发生什么?

在下面的示例代码中,我们打开一个文件描述符到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

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-os,python,unix,file-descriptor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值