int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);
struct rlimit {
rlim_t rlim_cur; /* Soft limit */
rlim_t rlim_max; /* Hard limit (ceiling for rlim_cur) */
};
setrlimit()和getrlimit()可以对查看或者设置进程对资源使用的限制,例如虚拟内存的最大值RLIMIT_AS,打开文件最大数RLIMIT_NOFILE等,具体请参见man手册.
getdtablesize()返回调用该函数的进程所能打开的最大文件数,是libc实现的一个函数,底层是通过调用getrlimit()实现的.在有些守护进程的代码中可以看到子进程调用该函数循环关闭所有的从父进程继承的文件描述符.
size = getdtablesize();
for(fd = 0; fd < size; fd++){
close(fd);
}
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
int main(void)
{
int ret = -1;
struct rlimit rl;
getrlimit(RLIMIT_NOFILE, &rl);
printf("rlim_t->rlim_cur is %d\n", rl.rlim_cur);
printf("rlim_t->rlim_max is %d\n", rl.rlim_max);
rl.rlim_cur = 1000;
rl.rlim_max = 1000;
setrlimit(RLIMIT_NOFILE, &rl);
getrlimit(RLIMIT_NOFILE, &rl);
printf("rlim_t->rlim_cur is %d\n", rl.rlim_cur);
printf("rlim_t->rlim_max is %d\n", rl.rlim_max);
ret = getdtablesize();
printf("ret is %d\n", ret);
return 0;
}
|
程序的输出如下:
rlim_t->rlim_cur is 1024
rlim_t->rlim_max is 1024
rlim_t->rlim_cur is 1000
rlim_t->rlim_max is 1000
ret is 1000