两个进程之间的互连

时间:2014-07-09 10:02:45

标签: python sockets unix-socket

我有两个进程,我需要在它们之间发送消息。这是第一个文件:

import socket
from info import socket1_filename, socket2_filename

socket1 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
socket1.bind(socket1_filename)
socket2 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
socket2.connect(socket2_filename)

这是第二个文件:

import socket
from info import socket1_filename, socket2_filename

socket1 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
socket1.connect(socket1_filename)
socket2 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
socket2.bind(socket2_filename)

这是info模块:

socket1_filename = '/tmp/socket1'
socket2_filename = '/tmp/socket2'

当然这件事不会奏效,这是一种僵局:

Traceback (most recent call last):
  File "process1.py", line 7, in <module>
    socket2.connect(socket2_filename)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 2] No such file or directory

那么,如果我需要能够在两个端点发送消息并接收消息,那么在进程之间实现简单互连的方法是什么?

1 个答案:

答案 0 :(得分:1)

正如Tichodroma所说,你需要重试。 定义超时(例如,10秒),并且在该时间未到期时,捕获socket.error并继续重试。如果在超时后仍然失败,则会大声失败。

在尝试两个进程bind之前,您需要connect,否则这将永远不会成功。

TIMEOUT= 10 #seconds
from datetime import datetime, timedelta
from time import sleep

timeout= datetime.now() + timedelta(seconds=TIMEOUT)

socket1 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
socket2 = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

socket2.bind(socket2_filename)

s1_done= False

while (not s1_done) and (datetime.now() < timeout):
    try:
        socket1.connect(socket1_filename)
        s1_done= True
    except socket.error:
        sleep(1)

if not s1_done:
    raise Exception("Failed to connect")