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?
4

1 に答える 1