如果您在使用套接字时遇到问题,您可能需要查看其他 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()
第一个过程将:
而第二个过程将只是:
如果您在两个不同的终端中执行上面的示例,您将在第一个终端中得到:
Received: Hello World!
Sending: Goodbye World!
在第二个中:
Sending: Hello World!
Received: Goodbye World!
注意:这只是一个例子。如果您需要双向通信,则使用两个命名管道会更方便,而不是在需要接收/发送消息时只打开一个用于读取/写入。