Skip to content

Instantly share code, notes, and snippets.

@anfernee
Created May 29, 2015 22:44
Show Gist options
  • Select an option

  • Save anfernee/b786f0685b3d64a5b611 to your computer and use it in GitHub Desktop.

Select an option

Save anfernee/b786f0685b3d64a5b611 to your computer and use it in GitHub Desktop.
# Demo of wrong handling of tcp connection
# if we shutdown the write end without closing the connection, the fd will
# still be there, while the network connection is gone. It will lead to an
# open fd leak. Basically it appears in lsof, not in netstat.
# lsof output:
# python 12594 vagrant 8u sock 0,7 0t0 74285 can't identify protocol
# ...
import socket
import os
import sys
import time
PORT = 9918
NUM = 1
sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sd.bind(('0.0.0.0', PORT))
sd.listen(5)
for i in range(NUM):
if os.fork() == 0:
sd.close()
cd = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
cd.connect(('127.0.0.1', PORT))
sys.exit()
print "Server process pid=%i" % (os.getpid(),)
sockets = []
for i in range(NUM):
(cd, address) = sd.accept()
# cd.setblocking(0) # don't change anything
sockets.append(cd)
os.system("lsof -p %i" % (os.getpid(),))
print 'rw'
for cd in sockets:
# cd.shutdown(socket.SHUT_WR) # can't identify protocol
cd.send('fxxxxx') # can't identify protocol
r = cd.recv(32)
print len(r)
for i in range(2):
time.sleep(1)
os.system("lsof -p %i" % (os.getpid(),))
# print 'close'
# for cd in sockets:
# cd.close()
for i in range(2):
time.sleep(1)
os.system("lsof -p %i" % (os.getpid(),))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment