Created
May 29, 2015 22:44
-
-
Save anfernee/b786f0685b3d64a5b611 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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