[仅读取一行时将丢弃命名管道的内容

问题描述 投票:0回答:1

我可能会误解,但是命名管道的行为应这样吗?

# consumer:
while True:
  queue: int = os.open('pipe', flags=os.O_RDONLY | os.O_NONBLOCK)
  with os.fdopen(queue, 'rb') as stream:
    readers, _, _ = select([stream], [], [])
    if readers:
      reader = readers.pop()
      contents: bytes = reader.readline().strip()

      if b'quit' == contents:
        break

      print(contents)

# producer:
fd = os.open(pipe, os.O_WRONLY | os.O_NONBLOCK)
ps = open(fd, 'wb')
for i in range(10):
  ps.write(str(i).encode())
  ps.write(os.linesep.encode())
ps.close()

我可以看到所有数据都已写入管道,一旦文件关闭,使用者中的选择就会将其拾取并开始读取...这是输出:

b'0'

[管道的其余所有部分都被丢弃,就像从未在那儿一样。这是预期的行为吗?我的期望是打印:

b'0'
b'1'
...
b'9'

我想使用命名管道进行进程间通信。脚本A向独立脚本B发送命令,然后可能再发送三个。 B应该拾取这些命令,然后一个接一个地执行它们。因此上面的代码。但是,只有第一个执行,其余的都消失了。命令与上面的示例不同。

  • cmd1 + cmd2
  • 10秒后
  • cmd3
  • 5秒后
  • cmd4 + cmd5 + cmd6
  • 20秒后
  • 退出

我该如何实现?

出于某些魔术原因,第一次选择挂起。

write(hello)
write(newline)
write(world)
flush()
print(hello) <- select hangs
... one eternity later ...
write(how)
write(newline)
write(are)
write(newline)
write(ya)
flush()
print(world) <- This should have been printed also without the new writes...
print(how) <- there were no new writes yet select didn't block as there was new data available for reading
print(are)
print(ya)

通过将1的超时值添加到select语句,我不需要伪写入来读取其余的管道。不知道这是否是一个选择限制,但肯定看起来像是可疑的,特别是从第二次开始按预期工作。

我可能会误解,但是命名管道的行为应该这样吗? #消费者:当True:队列:int = os.open('pipe',flags = os.O_RDONLY | os.O_NONBLOCK)与os.fdopen(queue,'rb')...

python python-3.x named-pipes
1个回答
0
投票

在该行:

© www.soinside.com 2019 - 2024. All rights reserved.