如何在Python中创建临时FIFO(命名管道)?这应该工作:
import tempfile
temp_file_name = mktemp()
os.mkfifo(temp_file_name)
open(temp_file_name, os.O_WRONLY)
# ... some process, somewhere, will read it ...
但是,我犹豫不决,因为Python Docs 11.6的大警告和潜在的删除,因为它已被弃用。
编辑:值得注意的是,我已经尝试了tempfile.NamedTemporaryFile
(并通过扩展tempfile.mkstemp
),但os.mkfifo
抛出:
OSError -17:文件已存在
当您在mkstemp / NamedTemporaryFile创建的文件上运行它时。
如果文件已经存在,os.mkfifo()
将失败,例外OSError: [Errno 17] File exists
,因此这里没有安全问题。使用tempfile.mktemp()
的安全问题是竞争条件,攻击者可能会在您自己打开它之前创建一个具有相同名称的文件,但由于os.mkfifo()
失败,如果该文件已经存在,这不是问题。
但是,由于mktemp()
已弃用,因此不应使用它。您可以使用tempfile.mkdtemp()
代替:
import os, tempfile
tmpdir = tempfile.mkdtemp()
filename = os.path.join(tmpdir, 'myfifo')
print filename
try:
os.mkfifo(filename)
except OSError, e:
print "Failed to create FIFO: %s" % e
else:
fifo = open(filename, 'w')
# write stuff to fifo
print >> fifo, "hello"
fifo.close()
os.remove(filename)
os.rmdir(tmpdir)
编辑:我应该明确指出,仅仅因为避免了mktemp()
漏洞,还有其他常见的安全问题需要考虑;例如攻击者可以在程序执行之前创建fifo(如果他们有合适的权限),如果没有正确处理错误/异常,可能会导致程序崩溃。
您可能会发现使用以下上下文管理器很方便,它会为您创建和删除临时文件:
import os
import tempfile
from contextlib import contextmanager
@contextmanager
def temp_fifo():
"""Context Manager for creating named pipes with temporary names."""
tmpdir = tempfile.mkdtemp()
filename = os.path.join(tmpdir, 'fifo') # Temporary filename
os.mkfifo(filename) # Create FIFO
yield filename
os.unlink(filename) # Remove file
os.rmdir(tmpdir) # Remove directory
你可以使用它,例如,像这样:
with temp_fifo() as fifo_file:
# Pass the fifo_file filename e.g. to some other process to read from.
# Write something to the pipe
with open(fifo_file, 'w') as f:
f.write("Hello\n")
如何使用
d = mkdtemp()
t = os.path.join(d, 'fifo')
如果它是在您的程序中使用,而不是任何外部,请查看Queue module。作为额外的好处,python队列是线程安全的。
实际上,mkstemp
所做的就是在一个循环中运行mktemp
并继续尝试专门创建直到它成功(参见stdlib源代码here)。你可以用os.mkfifo
做同样的事情:
import os, errno, tempfile
def mkftemp(*args, **kwargs):
for attempt in xrange(1024):
tpath = tempfile.mktemp(*args, **kwargs)
try:
os.mkfifo(tpath, 0600)
except OSError as e:
if e.errno == errno.EEXIST:
# lets try again
continue
else:
raise
else:
# NOTE: we only return the path because opening with
# os.open here would block indefinitely since there
# isn't anyone on the other end of the fifo.
return tpath
else:
raise IOError(errno.EEXIST, "No usable temporary file name found")
为什么不使用mkstemp()?
例如:
import tempfile
import os
handle, filename = tempfile.mkstemp()
os.mkfifo(filename)
writer = open(filename, os.O_WRONLY)
reader = open(filename, os.O_RDONLY)
os.close(handle)