如果你有套接字問題,你可能想看看替代的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!
注意:這只是一個示例。如果您需要雙向通信,當您需要接收/發送消息時,使用兩個命名管道而不是隻打開一個讀取/寫入將會更方便。