Unable to release control connections on OSX

Hi Nick. I've spent this whole weekend trying to diagnose an OSX specific integ error with stem without much success... https://trac.torproject.org/5917

I've finally narrowed the issue down to the following (note that you don't need stem at all, I'm just using it to start and stop the tor process)...

import os
import socket
import signal

import stem.process

tor_process = stem.process.launch_tor_with_config(
  tor_cmd = "../tor/src/or/tor",
  config = {'ControlPort': '7777'},
)

for i in xrange(5000):
  # connect to control socket
  control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  control_socket.connect(('127.0.0.1', 7777))
  
  # disconnect
  control_socket.shutdown(socket.SHUT_RDWR)
  control_socket.close()

try:
  tor_process.kill()
except AttributeError:
  # python 2.5 or earlier
  os.kill(tor_process.pid, signal.SIGTERM)

On Linux this works perfectly. However, on a mac (I'm running on macppc.torproject.org) the control socket goes into CLOSE_WAIT status, and eventually we're unable to make further connections...

74-95-122-145-Connecticut:stem atagar$ lsof -wnP | grep "127.0.0.1:7777"
Python  15052 atagar    5u    IPv4 0x23f966c        0t0      TCP 127.0.0.1:59076->127.0.0.1:7777 (SYN_SENT)
tor     15055 atagar    5u    IPv4 0x618f270        0t0      TCP 127.0.0.1:7777 (LISTEN)
tor     15055 atagar   13u    IPv4 0x616f270        0t0      TCP 127.0.0.1:7777->127.0.0.1:58947 (CLOSE_WAIT)
74-95-122-145-Connecticut:stem atagar$ python gloom.py 
Traceback (most recent call last):
  File "gloom.py", line 15, in <module>
    control_socket.connect(('127.0.0.1', 7777))
  File "<string>", line 1, in connect
socket.error: (60, 'Operation timed out')

At this point I'm completely out of ideas. Is this a Tor bug with releasing connections? An inability with python to actually shut down a socket? Am I simply doing this wrong?

This issue has been encountered by Karsten, Sathyanarayanan, and me interdependently (all on macs), and at present prevents Stem's integ tests from running there. Feel free to lower the priority or reassign back to me if I'm simply being stupid. :)