Python提示[Errno 32]Broken pipe導致線程crash錯誤解決方法

本文實例講述了Python提示[Errno 32]Broken pipe導致線程crash錯誤解決方法。分享給大家供大家參考。具體方法如下:

  1. 錯誤現象
    ThreadingHTTPServer 實現的 http 服務,如果客戶端在服務器返回前,主動斷開連接,則服務器端會報 [Errno 32] Broken pipe 錯,並導致處理線程 crash.
    下面先看個例子,python 版本: 2.7
    示例代碼
#!/usr/bin/env python
#!coding=utf-8
 
import os
import time
import socket
import threading
from BaseHTTPServer import HTTPServer ,BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
 
class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        """
        處理get請求
        """      
        query=self.path
        print "query: %s thread=%s" % (query, str(threading.current_thread()))
        
        #ret_str="<html>" + self.path + "<br>" + str(self.server) + "<br>" + str(self.responses) +  "</html>"
        ret_str="<html>" + self.path + "<br>" + str(self.server) +  "</html>"
        
        time.sleep(5)
        
        try:
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            self.wfile.write(ret_str)
        except socket.error, e:
            print "socket.error : Connection broke. Aborting" + str(e)
            self.wfile._sock.close()  # close socket
            self.wfile._sock=None
            return False
       
        print "success prod query :%s" % (query)
        return True
 
#多線程處理
class ThreadingHTTPServer(ThreadingMixIn,HTTPServer):
    pass
    
if __name__ == '__main__':
    serveraddr = ('',9001)
 
    ser = ThreadingHTTPServer(serveraddr,RequestHandler)
    ser.serve_forever()
    sys.exit(0)

運行服務

./thread_http_server_error.py
第1次 curl ,等待返回
[~]$curl -s 'http://10.232.41.142:9001/hello1′
<html>/hello1<br><__main__.ThreadingHTTPServer instance at 0x37483b0></html>[~]$
此時服務器端輸出日誌如下:
$./thread_http_server_error.py
query: /hello1 thread=
search041142.sqa.cm4.tbsite.net – - [15/May/2014 15:02:27] “GET /hello1 HTTP/1.1″ 200 -
success prod query :/hello1

第2次 curl ,不等待返回,ctrl +C 來模擬客戶端斷開

 [~]$curl -s 'http://10.232.41.142:9001/hello2′
[~]$ ctrl+C

此時服務器端輸出日誌如下:
query: /hello2 thread=
search041142.sqa.cm4.tbsite.net – - [15/May/2014 15:33:10] “GET /hello2 HTTP/1.1″ 200 -
socket.error : Connection broke. Aborting[Errno 32] Broken pipe
—————————————-
Exception happened during processing of request from ('10.232.41.142′, 48769)
Traceback (most recent call last):
File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/SocketServer.py”, line 582, in process_request_thread
self.finish_request(request, client_address)
File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/SocketServer.py”, line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/SocketServer.py”, line 639, in init
self.handle()
File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/BaseHTTPServer.py”, line 337, in handle
self.handle_one_request()
File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/BaseHTTPServer.py”, line 326, in handle_one_request
self.wfile.flush() #actually send the response if not already done.
File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/socket.py”, line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
AttributeError: ‘NoneType’ object has no attribute ‘sendall’
2. 原因分析

“[Errno 32] Broken pipe “ 產生的原因還是比較明確的,由於 client 在服務器返回前主動斷開連接,所以服務器在返回時寫 socket 收到SIGPIPE報錯。雖然在我們的程序中也對異常進行了處理,將handler 的 wfile._sock 對象close 掉 ,但python 的庫裏BaseHTTPServer.py中BaseHTTPRequestHandler 類的成員函數handle_one_request還是會直接調用 wfile.flush ,而沒有判斷 wfile 是否已經 close。
複製代碼代碼如下:

def handle_one_request(self):
    """Handle a single HTTP request.
 
    You normally don't need to override this method; see the class
    __doc__ string for information on how to handle specific HTTP
    commands such as GET and POST.
 
    """
    try:
        self.raw_requestline = self.rfile.readline(65537)
        if len(self.raw_requestline) > 65536:
            self.requestline = ''
            self.request_version = ''
            self.command = ''
            self.send_error(414)
            return
        if not self.raw_requestline:
            self.close_connection = 1
            return
        if not self.parse_request():
            # An error code has been sent, just exit
            return
        mname = 'do_' + self.command
        if not hasattr(self, mname):
            self.send_error(501, "Unsupported method (%r)" % self.command)
            return
        method = getattr(self, mname)
        method()
        #沒有判斷 wfile 是否已經 close 就直接調用 flush()
        self.wfile.flush() #actually send the response if not already done.
    except socket.timeout, e:
        #a read or a write timed out.  Discard this connection
        self.log_error("Request timed out: %r", e)
        self.close_connection = 1
        return
  1. 解決辦法
    只要在RequestHandler重載其基類BaseHTTPRequestHandler的成員函數handle_one_reques(),在調用 wfile.flush() 前加上 wfile 是否已經 close 即可。
#!/usr/bin/env python
#!coding=utf-8
import os
import time
import socket
import threading
from BaseHTTPServer import HTTPServer ,BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn

class RequestHandler(BaseHTTPRequestHandler):
    
    def handle_one_request(self):
        """Handle a single HTTP request.
 
        You normally don't need to override this method; see the class
        __doc__ string for information on how to handle specific HTTP
        commands such as GET and POST.
 
        """
        try:
            self.raw_requestline = self.rfile.readline(65537)
            if len(self.raw_requestline) > 65536:
                self.requestline = ''
                self.request_version = ''
                self.command = ''
                self.send_error(414)
                return
            if not self.raw_requestline:
                self.close_connection = 1
                return
            if not self.parse_request():
                # An error code has been sent, just exit
                return
            mname = 'do_' + self.command
            if not hasattr(self, mname):
                self.send_error(501, "Unsupported method (%r)" % self.command)
                return
            method = getattr(self, mname)
            print "before call do_Get"
            method()
            #增加 debug info 及 wfile 判斷是否已經 close
            print "after call do_Get"
            if not self.wfile.closed:
                self.wfile.flush() #actually send the response if not already done.
            print "after wfile.flush()"
        except socket.timeout, e:
            #a read or a write timed out.  Discard this connection
            self.log_error("Request timed out: %r", e)
            self.close_connection = 1
            return
    
    def do_GET(self):
        """
        處理get請求
        """
        query=self.path
        print "query: %s thread=%s" % (query, str(threading.current_thread()))
 
        ret_str="<html>" + self.path + "<br>" + str(self.server) +  "</html>"
 
        time.sleep(5)
        
        try:
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()         
            self.wfile.write(ret_str)
        except socket.error, e:
            print "socket.error : Connection broke. Aborting" + str(e)
            self.wfile._sock.close()
            self.wfile._sock=None
            return False
       
        print "success prod query :%s" % (query)
        return True
 
#多線程處理
class ThreadingHTTPServer(ThreadingMixIn,HTTPServer):
    pass
    
if __name__ == '__main__':
    serveraddr = ('',9001)
 
    ser = ThreadingHTTPServer(serveraddr,RequestHandler)
    ser.serve_forever()
    sys.exit(0)

運行服務
./thread_http_server.py
curl ,不等待返回,ctrl +C 來模擬客戶端斷開

[~]$curl -s 'http://10.232.41.142:9001/hello2'
[~]$ ctrl+C

此時服務器端輸出日誌如下:

$./thread_http_server.pybefore call do_Get
query: /hello2 thread=<Thread(Thread-1, started 1103210816)>
search041142.sqa.cm4.tbsite.net - - [15/May/2014 15:54:09] "GET /hello2 HTTP/1.1" 200 -
socket.error : Connection broke. Aborting[Errno 32] Broken pipe
after call do_Get
after wfile.flush()

推薦我們的python學習基地,看老程序是如何學習的!從基礎的python腳本、爬蟲、django、數據挖掘等編程技術,工作經驗,還有前輩精心爲學習python的小夥伴整理零基礎到項目實戰的資料,!每天都有程序員定時講解Python技術,分享一些學習的方法和需要留意的小細節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章