Python提示[Errno 32]Broken pipe导致线程crash错误解决方法


Posted in Python onNovember 19, 2014

本文实例讲述了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

3. 解决办法

只要在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 相关文章推荐
python计算对角线有理函数插值的方法
May 07 Python
python处理大数字的方法
May 27 Python
分享Python文本生成二维码实例
Jan 06 Python
python在线编译器的简单原理及简单实现代码
Feb 02 Python
使用python3+xlrd解析Excel的实例
May 04 Python
通过Py2exe将自己的python程序打包成.exe/.app的方法
May 26 Python
tensorflow: variable的值与variable.read_value()的值区别详解
Jul 30 Python
python的debug实用工具 pdb详解
Jul 12 Python
python实现引用其他路径包里面的模块
Mar 09 Python
如何基于python把文字图片写入word文档
Jul 31 Python
Python 解析库json及jsonpath pickle的实现
Aug 17 Python
Python多分支if语句的使用
Sep 03 Python
python中urllib模块用法实例详解
Nov 19 #Python
python统计一个文本中重复行数的方法
Nov 19 #Python
python通过zlib实现压缩与解压字符串的方法
Nov 19 #Python
python判断字符串是否纯数字的方法
Nov 19 #Python
python使用any判断一个对象是否为空的方法
Nov 19 #Python
python编写暴力破解FTP密码小工具
Nov 19 #Python
用python读写excel的方法
Nov 18 #Python
You might like
杏林同学录(一)
2006/10/09 PHP
php 冒泡排序 交换排序法
2011/05/10 PHP
PHP中将数组转成XML格式的实现代码
2011/08/08 PHP
php使用curl模拟登录后采集页面的例子
2013/11/04 PHP
php中http与https跨域共享session的解决方法
2014/12/20 PHP
js获取div高度的代码
2008/08/09 Javascript
javascript管中窥豹 形参与实参浅析
2011/12/17 Javascript
自己实现string的substring方法 人民币小写转大写,数字反转,正则优化
2012/09/02 Javascript
jquery 合并内容相同的单元格(示例代码)
2013/12/13 Javascript
js无刷新操作table的行和列
2014/03/27 Javascript
Bootstrap精简教程中秋大放送
2016/09/15 Javascript
JSON 对象未定义错误的解决方法
2016/09/29 Javascript
详解js运算符单竖杠“|”与“||”的用法和作用介绍
2016/11/04 Javascript
jQuery插件HighCharts绘制2D半圆环图效果示例【附demo源码下载】
2017/03/09 Javascript
JavaScript设计模式之单例模式详解
2017/06/09 Javascript
jQuery实现动态给table赋值的方法示例
2017/07/04 jQuery
vue实现密码显示隐藏切换功能
2018/02/23 Javascript
Vue基于vuex、axios拦截器实现loading效果及axios的安装配置
2019/04/26 Javascript
js设置鼠标悬停改变背景色实现详解
2019/06/26 Javascript
vue-router 2.0 跳转之router.push()用法说明
2020/08/12 Javascript
Python简单检测文本类型的2种方法【基于文件头及cchardet库】
2016/09/18 Python
Python PyQt5实现的简易计算器功能示例
2017/08/23 Python
Python模块WSGI使用详解
2018/02/02 Python
深入浅析Python传值与传址
2018/07/10 Python
符合语言习惯的 Python 优雅编程技巧【推荐】
2018/09/25 Python
python2使用bs4爬取腾讯社招过程解析
2019/08/14 Python
python如何通过闭包实现计算器的功能
2020/02/22 Python
Python 多进程、多线程效率对比
2020/11/19 Python
全球最受追捧的运动服品牌领先数字目的地:Stylerunner
2020/11/25 全球购物
广播电视新闻学专业应届生求职信
2013/10/08 职场文书
领导的自我鉴定
2013/12/28 职场文书
2014新课程改革心得体会
2014/03/10 职场文书
教师节演讲稿
2014/05/06 职场文书
经理岗位职责
2015/02/02 职场文书
MySQL非空约束(not null)案例讲解
2021/08/23 MySQL
Apache Hudi数据布局黑科技降低一半查询时间
2022/03/31 Servers