Skip to main content

A possible [Errno 32] Broken pipe when using socket._fileobject

In Python 2.x, socket object have an makefile() method to provide you a file like object. Please do use it carefully, if the socket itself closed unexpectedly, the fileobject may not know the connection is actually closed. So some buffered write is not going to be performed correctly.

For example, considering the following code:
import socket


sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(('google.com', 80))
wfile = sock.makefile('w')
wfile.write('a')
sock.shutdown(socket.SHUT_WR)
wfile.close()


It will cause exceptions as below:
Traceback (most recent call last):
  File "socket_shut.py", line 9, in 
    wfile.close()
  File "/usr/lib/python2.7/socket.py", line 279, in close
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
socket.error: [Errno 32] Broken pipe

The reason is that wfile has some buffered write, when calling wfile.close() it will flush the buffer, cause a Broken pipe error.

Comments