I have two processes and I need to send messages between them. Here's the first file:
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)
And here's the second file:
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)
And here's the info module:
socket1_filename = '/tmp/socket1'
socket2_filename = '/tmp/socket2'
Of course this thing won't work, it's kind of a deadlock:
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
So what is the way to implement simple interconnection between processes if I need to be able to send messages and receive them in both endpoints?
-
1Perhaps catch the exception and retry.user1907906– user19079062014年07月09日 10:05:22 +00:00Commented Jul 9, 2014 at 10:05
1 Answer 1
As Tichodroma said, you'll need to retry.
Define a timeout (say, 10 seconds), and, while that time doesn't expire, catch socket.error and keep retrying. If it still fails after the timeout, fail loudly.
You'll need to bind before you attempt to connect on both processes, otherwise this will never succeed.
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")
2 Comments
bind first, connect after - otherwise it will be a deadlock. see the code I included