命令介绍
prlimit - get and set a process resource limits.
prlimit
这个命令用来设置或者获取某进程的资源限制数.
如临时设置某进程可打开的文件数,
prlimit --pid=9999 --nofile=102400:102400
, 这条命令表示设置pid为9999的进程的可打开的文件最大数为102400(soft & hard).
还有其他选项, 基本和ulimit
一致:
prlimit --help
用法:
prlimit [选项] [-p PID]
prlimit [选项] 命令
常规选项:
-p, --pid <pid> 进程 id
-o, --output <列表> 定义要使用的输出列
--noheadings 不打印标题
--raw 使用原生输出格式
--verbose 详尽输出
-h, --help 显示此帮助并退出
-V, --version 输出版本信息并退出
资源选项:
-c, --core 创建核心文件的最大尺寸
-d, --data 进程数据段的最大尺寸
-e, --nice 允许提升的最大 nice 优先级
-f, --fsize 进程写文件的最大尺寸
-i, --sigpending 挂起(pending)信号的最大数量
-l, --memlock 内存中进程锁的最大数量
-m, --rss (内存虚拟页)驻留集的最大数量
-n, --nofile 打开文件的最大数量
-q, --msgqueue POSIX 消息队列的最大字节数
-r, --rtprio 最大实时调度优先级
-s, --stack 最大栈(stack)尺寸
-t, --cpu 最长 CPU 时间(秒)
-u, --nproc 最多用户进程数量
-v, --as 虚拟内存大小
-x, --locks 文件锁的最大数量
-y, --rttime 实时调度时进程调度的 CPU
(间隔)时间(毫秒)
可用列(用于 --output):
DESCRIPTION 资源描述
RESOURCE 资源名称
SOFT 软限制
HARD 硬限制(触顶)
UNITS 单位
更多信息请参阅 prlimit(1)。
实验
我们以 -n(–nofile)为例来测试一下:
准备示例程序
nofile.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main() {
int i = 0;
char filename[10]= {0};
FILE* file;
while (1) {
sprintf(filename, "%d.txt", i);
file = fopen(filename, "w+");
if (!file) {
perror(filename);
exit(1);
}
printf("created filename=%s\n", filename);
// do not close
sleep(1);
i++;
}
return 0;
}
上述程序中, 我们每秒打开一个文件且不关闭, 如果打开失败, 则打印errmsg并退出.
实验过程
# 1. 编译nofile.c
$ gcc -g -Wall -o nofile.out nofile.c
# 2. 运行nofie.out
./nofile.out
# 3. 再开一个终端
$ ps -ef|grep nofile
root 15760 10805 0 14:04 pts/1 00:00:00 ./nofile.out
# 3.1 使用prlimit限制其nofile
$ prlimit --pid 15760 --nofile=50
# 3.2 查看prlimit限制nofile, 发现已生效(也可通过 prlimit --pid 15760 --nofile来查看)
$ cat /proc/15760/limits
Limit Soft Limit Hard Limit Units
...
Max open files 50 50 files
...
# 4. 观察结果:
created filename=0.txt
created filename=1.txt
...
created filename=46.txt
47.txt: Too many open files
linux进程默认打开stdin
, stdout
, stderr
三个文件, 再加上打开的{0, 1, …46}.txt共50个文件, 所以在打开
第51个文件(47.txt)时报错: 47.txt: Too many open files
补充
实验中还发现, 当nofile.out已经打开20多个文件时, 此时使用prlimit
设置其nofile为20, 会令nofile.out相应的进程立刻退出(报错: 23.txt: Too many open files).
总结
prlimit
命令可以用来动态设置进程的一些资源限制, 可以在不重启服务器的情况下实现一些效果, 非常好用.
(完)