我正忙着为我的一个项目找出一些东西,但是却挂了一个问题:
我正在使用FIFO操作从一个模块向另一个模块发送'信号'(简单T / F)。一个模块打开FIFO以写入它,另一个模块打开FIFO以从中读取。这里的目标是在写入模块接收到命令时立即读取并显示读取模块。写入模块打开FIFO,但读取模块似乎没有这样做。
我正在尝试做甚么可能吗?我试图在_threads中旋转两个操作,以便在每个模块中保持多个进程。请注意,为了简洁起见,这两个模块都在我没有包含的类中(解释'self')。
def pipe_relay(self):
FIFO = 'pipe_relay'
thread_num = num
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
while self.relay_switch:
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
while self.relay_switch:
data = fifo.write(signal)
if len(data) == 0:
print("Writer is closed")
break
print('Write: "{0}"'.format(data))
我意识到我不想用我投入的数据连续写入FIFO,所以我删除了while()语句。现在,似乎FIFO根本不会打开......
def pipe_relay(self, num, signal):
FIFO = 'pipe_relay'
thread_num = num
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
print("Opening FIFO...")
# does not proceed past this point
with open(FIFO, mode = 'w') as fifo:
print("FIFO opened")
data = fifo.write(signal)
if len(data) == 0:
print("Writer is closed")
print('Write: "{0}"'.format(data))
fifo.close()
def pipe_receive(self):
FIFO = 'pipe_relay'
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
# module proceeds to here, but no further
with open(FIFO) as fifo:
print("FIFO opened (receiver)")
while True:
data = fifo.read()
if len(data) == 0:
print("Writer is closed")
break
print('Read signal: "{0}"'.format(data))
self.DISPLAY['text'] = data
print("this is in 'pipe_receieve'")
修改
运行Ubuntu 17.04。该项目是为Python 3.5解释器编写的。
答案 0 :(得分:2)
以下是使用<div class="ancestor">
<div class="parent">
<p class="child">
Lorem ipsum dolor sit amet, consectetur adipisicing.
</p>
</div>
</div>
编写的简单发送和获取代码段
注释掉Python 3.5.2
行并查看行为上的差异
使用fifo.flush()
,获取代码与发送代码一起运行
没有它,get代码在fifo关闭之前不会做出反应
<强> send.py 强>
flush
<强> get.py 强>
import sys, os, time
path = "/tmp/my.fifo"
try:
os.mkfifo(path)
except:
pass
try:
fifo = open(path, "w")
except Exception as e:
print (e)
sys.exit()
x = 0
while x < 5:
fifo.write(str(x))
fifo.flush()
print ("Sending:", str(x))
x+=1
time.sleep(3)
print ("Closing")
fifo.close()
try:
os.unlink(fifo)
except:
pass
答案 1 :(得分:0)
我有点惊讶的是代码没有引发异常。在您的作者中,您定期open(FILO)
,而不指定mode
参数。根据{{3}},mode
默认为r
(只读),因此我希望fifo.write(signal)
提升IOError
。是否有异常被捕?
无论哪种方式,都应该在编写器端添加mode="w"
以打开FIFO进行写入。
答案 2 :(得分:0)
除了要求发送模块的'w'
选项外,您可能还遇到了发送或接收器未连接的问题。为了让另一个进程使用fifo,发送方和接收方都必须打开fifo句柄。
在fifo上查看linux documentation。如果接收器没有监听,你会得到一个SIGPIPE,它通常会终止一个进程,但在python的情况下,它会等到接收器连接完毕。
如果您的发件人已经死亡且收听者仍处于活动状态,则会收到EOF并停止阅读。