如果你有套接字问题,你可能想看看替代的IPC机制。例如,named pipes让两个进程进行通信,就好像它们只是向文件写入/读取一样。
下面的例子演示了如何命名管道的创建,以及如何在两个不同的进程打开阅读和写作:
import os
pipe_name = '/tmp/ipc'
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
try:
with open(pipe_name) as f:
print 'Received:', f.read()
with open(pipe_name, 'w') as f:
message = 'Goodbye World!'
print 'Sending:', message
f.write(message)
finally:
os.remove(pipe_name)
else:
with open(pipe_name, 'w') as f:
message = 'Hello World!'
print 'Sending:', message
f.write(message)
with open(pipe_name) as f:
print 'Received:', f.read()
第一进程也将:
- 创建命名管道
- 收到消息
- 发送另一个消息
- 删除点子È
而Seconde系列过程将只是:
如果在两个不同的终端执行上面的例子中,在第一个你会得到:
Received: Hello World!
Sending: Goodbye World!
和第二个:
Sending: Hello World!
Received: Goodbye World!
注意:这只是一个示例。如果您需要双向通信,当您需要接收/发送消息时,使用两个命名管道而不是只打开一个读取/写入将会更方便。