[issue19530] cross thread shutdown of UDP socket exhibits unexpected behavior

mpb report at bugs.python.org
Sun Nov 10 01:41:02 CET 2013


mpb added the comment:

After some research...

> Which is normal, since UDP sockets aren't connected.

But UDP sockets can be connected!

If I connect the UDP sockets, then shutdown succeeds (no exception is raised), but recvfrom still appears to succeed, returning a zero length message with a bogus address family, IP address and port.  (Bogus even if I set them to zero before the call!)

FYI, the FreeBSD (and OpenBSD) shutdown manpages anticipate calling shutdown on DGRAM sockets.  And the Linux connect manpage discusses connecting DGRAM sockets.

Here is the updated Python code.  I do expect to try to report this upstream.  (Also, I now have C/pthreads code, if you want to see it.  As expected, C behaves identically.)

----

import socket, threading, time

fd_0 = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
fd_0.bind    (('localhost', 8000))
fd_0.connect (('localhost', 8001))

fd_1 = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
fd_1.bind    (('localhost', 8001))
fd_1.connect (('localhost', 8000))

def thread_main ():
  for i in range (3) :
    # print ('recvfrom  blocking ...')                                          
    recv, remote_addr = fd_0.recvfrom (1024)
    print ('recvfrom  %s  %s' % (recv, remote_addr))

def main ():
  fd_1.send (b'test')
  fd_1.send (b'')
  fd_0.shutdown (socket.SHUT_RD)

thread = threading.Thread ( target = thread_main )
thread.start ()
time.sleep (0.5)
main ()
thread.join ()
print ('exiting')

----

And the code outputs:
recvfrom  b'test'  ('127.0.0.1', 8001)
recvfrom  b''  ('127.0.0.1', 8001)
recvfrom  b''  (36100, b'\xe4\xc6\xf0^7\xe2\x85\xf8\x07\xc1\x04\x8d\xe4\xc6')
exiting

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19530>
_______________________________________


More information about the Python-bugs-list mailing list