Python 验证 Linux 系统描述符是有限的

本文通过Python演示了Linux系统中文件描述符的数量限制,并展示了如何批量打开文件直至达到系统上限,之后介绍了如何查看当前进程打开的文件详情及系统限制,最后演示了如何释放这些资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Linux Python 批量打开文件

[root@Sybil ~]#python3
Python 3.9.8 (main, Mar 23 2022, 21:03:31) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = []
>>> for i in range(2000):
...     list1.append(open('/root/tangtang'))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
OSError: [Errno 24] Too many open files: '/root/tangtang'
>>> 

2、查看 Linux 文件打开明细

[root@Sybil ~]#ps -aux | grep python
root        757  0.0  1.5 358744 29516 ?        Ssl  20:39   0:00 /usr/bin/python2 -Es /usr/sbin/firewalld --nofork --nopid
root       1096  0.0  1.0 574284 19436 ?        Ssl  20:39   0:01 /usr/bin/python2 -Es /usr/sbin/tuned -l -P
root      57675  0.0  0.6 142940 12980 pts/1    S+   22:34   0:00 python3
root      59491  0.0  0.0 112816   980 pts/0    S+   23:09   0:00 grep --color=auto python
[root@Sybil ~]#lsof -p 57675 | grep python | grep tangtang | wc -l
1021

3、关闭 Python 打开的文件对象

>>> for x in list1:
...     x.close()
... 

4、验证 Linux 的 lsof

[root@Sybil ~]#lsof -p 57675 | grep python | grep tangtang | wc -l
0

5、查看 Linux 系统各种限制

[root@Sybil ~]#ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7183
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 7183
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值