代碼示例支持 |
---|
平臺: Centos 6.3 |
Python: 2.7.14 |
代碼示例: 菜單 - Python踩坑指南代碼示例 |
長期運行的daemon進程或者socket測試類進程, 常常遇到的坑是:shell
IOError: [Errno 24] Too many open files
bash
即進程遇到 IO 錯誤, 沒法打開更多的文件.socket
通常從兩個方面入手:測試
a. 誰打開誰關閉是個普適的原則:優化
# with 語法會在生命週期後自動關閉打開的文件 FD with open('xxxx_path.file', 'w') as fhandle: fhandle.dosth()
b. 檢查文件 FD 是否存在泄漏設計
系統設計階段通常會預估系統整體可打開的 FD 狀況. 當出現以下狀況時可能出現了泄漏 BUGcode
Python 基礎庫 CUP 提供對進程打開 FD 的支持, 詳見示例代碼.生命週期
以 Centos 6.3 Linux系統
爲例, 查看 /etc/security/limits.conf 得到系統軟硬限資源進程
* soft nofile 10240 * hard nofile 10240
其中, 用戶不能突破系統的硬線 hard nofile limit
.
用戶也能夠經過 shell 命令 ulimit -n 來限定該 shell 啓動的全部進程的 nofile
ulimit -a
能夠查看當前用戶被設定的限制, 示例:
[test@agent1 ~]$ ulimit -a core file size (blocks, -c) 0 ....... open files (-n) 10240 ..... virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
Life is short. We use Python.