您的位置:首页 > 运维架构 > Linux

如何验证linux进程打开文件数的默认最大值(通常是1024)? 知识点: ulimit; watch -n 1 'ls -l /proc/xxx/fd | wc -l'

2016-07-02 12:13 841 查看
       曾经在某公司的笔试题中出现了这样一个题目:linux进程打开文件数的默认最大值是多少? 我当时想, 这不是为难人么? 谁记得住呢? 用ulimit命令查一下不就知道了么? 其实, 本题不过是在考一个简单的常识。 这种题放在校招题目中, 毫无意义, 如果是社招, 那倒是情有可原。

       我们来用命令查一下:

taoge@localhost Desktop> 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) 3894
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) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 1024
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
taoge@localhost Desktop>
       看来, 在我的机器上确实是1024.  那怎么进行实际验证呢? 有的朋友可能会说: 直接用程序去读取啊? 其实这并没有什么卵用, 因为程序读取的数据肯定就是上述数据, 读取的是一个东西。 
       我相当了一种验证方法: 让程序不断打开文件, 看啥时候到顶, 如下(程序是测试程序, 不要close(fd)):

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
while(1)
{
int randNum = 0;
int fd = open("/dev/urandom", O_RDONLY);
if(-1 == fd)
{
printf("error\n");
return 1;
}

read(fd, (char *)&randNum, sizeof(int));

printf("pid is %u, randNum is %d\n", getpid(), randNum);

usleep(100000);
}

return 0;
}
     编译运行, 并在另一个窗口中观察(watch -n 1 'ls -l /proc/14249/fd | wc -l'):



       可以看出, 随着程序的运行(左边), 句柄在消耗在增长(右边), 当程序最后出现error的时候, 句柄消耗的数量刚好接近1024  (为什么 ls -l /proc/14249/fd | wc -l得出的值不是准确的1024, 大家可以思考一下!) 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: