Python提示[Errno 32]Broken pipe导致线程crash错误解决方法
作者:shichen2014 发布时间:2022-12-02 02:20:42
本文实例讲述了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程序设计有所帮助。


猜你喜欢
- 1、在模块中,我们需要判断__name__是否被赋值为“__main__”。python fibo.py <arguments>
- 向量化与for循环耗时对比深度学习中,可采用向量化替代for循环,优化耗时问题对比例程如下,参考Andrew NG的课程笔记import t
- 设法让用户happy吧~只要你的设计让用户乐了,产品的个性就得到了一次彰显,而用户对网站的情感就会获得一次升华,看看下面的知名网站的人性化设
- #!/bin/sh#code by scpman#功能:检查并修复mysql数据库表#将此脚本加到定时中,脚本执行时,等会读库,列出要修复的
- 什么是状态机?关于状态机的一个极度确切的描述是它是一个有向图形,由一组节点和一组相应的转移函数组成。状态机通过响应一系列事件而“运行”。每个
- 一、前言最近本都是开开心心的打开电脑写一些祖传BUG但一个报错阻碍了我写BUG的进度!这年代还有能阻碍我写BUG的报错???二、解决过程一个
- 首先我们先引入requests模块import requests一、发送请求r = requests.get('https://ap
- 本文实例为大家分享了jQuery轮播效果展示的具体代码,供大家参考,具体内容如下jQ代码: 在写jQuery代码之前一定要先导库,此处我用的
- 功能:读取txt文本,然后将目的字符串标红,再将处理过的字符串写入docx中txt文本内容:啊打发发烧鳌太路线点击点击诶的骄傲计划将鳌太标红
- 本文实例为大家分享了vue实现拖拽交换位置的具体代码,供大家参考,具体内容如下<template> <div
- 在介绍GROUP BY 和 HAVING 子句前,我们必需先讲讲sql语言中一种特殊的函数:聚合函数,例如SUM, COUNT, MAX,
- 介绍Django是一个Web框架——一套用于帮助开发交互式网站的工具。Django能够响应网页请求,还能让我们更轻松地读写数据库、管理用户等
- matplotlib简介matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行
- 为什么在facebook交友会更容易?facebook与传统的BSP(Blog Service Provider)到底有什么不同?是因为它有
- 手写数字识别算法的设计与实现本文使用python基于TensorFlow设计手写数字识别算法,并编程实现GUI界面,构建手写数字识别系统。这
- 1.join函数的语法及用法(1)语法:'sep'.join(sep_object)参数说明sep:分割符,可为&l
- <script> function isIPv6(str) { return str.mat
- #-*- coding:utf-8 -*- from win32com.client import Dispatch import time
- 在开发的过程中,几乎不可能一次性就能写出毫无破绽的程序,断点调试代码是一个普遍的需求。作为前端开发工程师,以往我们开发的JavaScript
- 本文实例讲述了Python基于TCP实现会聊天的小机器人功能。分享给大家供大家参考,具体如下:一 代码1、服务端程序import socke