最近寫了一個 flask 程序,是在一個進程的兩個子進程中同時起 flask server, 發現在windows下不會報錯,但是在linux下會監聽失敗。
Traceback (most recent call last):
File "/usr/lib64/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib64/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "test_mutiprocess_timeout.py", line 38, in fun1
api_construct()
File "test_mutiprocess_timeout.py", line 27, in api_construct
app.run("0.0.0.0")
File "/usr/lib/python2.7/site-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/lib/python2.7/site-packages/werkzeug/serving.py", line 691, in run_simple
inner()
File "/usr/lib/python2.7/site-packages/werkzeug/serving.py", line 653, in inner
fd=fd)
File "/usr/lib/python2.7/site-packages/werkzeug/serving.py", line 547, in make_server
passthrough_errors, ssl_context, fd=fd)
File "/usr/lib/python2.7/site-packages/werkzeug/serving.py", line 461, in __init__
HTTPServer.__init__(self, (host, int(port)), handler)
File "/usr/lib64/python2.7/SocketServer.py", line 420, in __init__
self.server_activate()
File "/usr/lib64/python2.7/SocketServer.py", line 439, in server_activate
self.socket.listen(self.request_queue_size)
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use
同時在 windows 上發現,即使同時運行我的程序兩次,也可以正常工作。經過查閱資料以後發現,是 linux 和 windows 對端口監聽的處理不同。
inux下,兩個tcp的socket不能綁定同一個端口;而如果使用SO_REUSEADDR選項,兩個udp的socket可以綁定同一個端口。
windows下
兩個tcp的socket不能綁定同一個端口,唯一例外的是監聽socket。
參考:
http://blog.csdn.net/shuixin536/article/details/8917493