Open Files – ulimit, lsof
ulimit常用方法
ulimit -Sn [number]
显示或设置最大打开句柄数(soft
限制),只对当前Shell生效ulimit -Hn [number]
显示或设置最大打开句柄数(hard
限制),只对当前Shell生效ulimit -n [number]
不加number时等于ulimit -Sn
,加number时同时设置soft and hard
最大打开句柄数上述设置只对当前Shell生效,需要永久生效可以改
/etc/security/limits.conf
, 详细可以查看说明man limits.conf
查看进程当前设置
cat /proc/{pid}/limits |grep 'Max open files'
pid为进程号
ulimit soft/hard的区别
soft不能高于hard,否则设置会报错
hard一旦设置,就不可以在修改为更大的值,可以修改为更小的值,而soft值可以随意修改
参考
man limits.conf
<type>
hard
for enforcing hard resource limits. These limits are set by the superuser and enforced by the Kernel. The user cannot raise his
requirement of system resources above such values.
soft
for enforcing soft resource limits. These limits are ones that the user can move up or down within the permitted range by any
pre-existing hard limits. The values specified with this token can be thought of as default values, for normal system usage.
-
for enforcing both soft and hard resource limits together.
Note, if you specify a type of '-' but neglect to supply the item and value fields then the module will never enforce any limits on
the specified user/group etc. .
lsof常用方法
lsof filename 显示打开指定文件的所有进程,可以用于判断文件是否有其他用户在使用
lsof -p pid 显示本进程打开的文件列表,可以查看进程打开了那些文件,寻找二进制文件目录,定位服务未释放的文件等
lsof -u username 显示所属user进程打开的文件
lsof -c command 显示COMMAND列中包含指定字符的进程所有打开的文件
lsof -d FD 显示指定文件描述符的进程
lsof找回删除的文件
服务pid为12766
$ lsof -p 12766 [9/171]
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
writefile 12766 wei cwd DIR 8,2 4096 3151154 /home/test/ulimit
writefile 12766 wei rtd DIR 8,2 4096 2 /
writefile 12766 wei txt REG 8,2 1572986 2102508 /home/test/ulimit/writefile
writefile 12766 wei 0u CHR 136,2 0t0 5 /dev/pts/2
writefile 12766 wei 1u CHR 136,2 0t0 5 /dev/pts/2
writefile 12766 wei 2u CHR 136,2 0t0 5 /dev/pts/2
writefile 12766 wei 3w REG 8,2 528 2102212 /tmp/test.txt (deleted)
$ cat /proc/12766/fd/3
Row:001 my name is:/tmp/test.txt
Row:002 my name is:/tmp/test.txt
Row:003 my name is:/tmp/test.txt
Row:004 my name is:/tmp/test.txt
注意这行:
writefile 12766 wei 3w
REG 8,2 528 2102212 /tmp/test.txt (deleted)
文件test.txt已经被删除,句柄为3,通过路径/proc/{进程号}/fd/{句柄号}仍然可以查看文件内容