0

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?

asked Jul 9, 2014 at 10:02
1
  • 1
    Perhaps catch the exception and retry. Commented Jul 9, 2014 at 10:05

1 Answer 1

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")
answered Jul 9, 2014 at 10:13
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, it was very dumb question. Thank you guys!
@DmitryMikhaylov don't forget to always bind first, connect after - otherwise it will be a deadlock. see the code I included

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.