fd的數量決定了fd的最大值
在Linux下,系統全部能夠開啟的fd總數為:
/proc/sys/fs/file-max,取決於記憶體
The file-max file /proc/sys/fs/file-max sets the maximum number of file-handles that the Linux kernel will allocate. We generally tune this file to improve the number of open files by increasing the value of /proc/sys/fs/file-max to something reasonable like 256 for every 4M of RAM we have: i.e. for a machine with 128 MB of RAM, set it to 8192 - 128/4=32 32*256=8192.
/proc/sys/fs/file-nr 記錄系統中fd的使用方式,已指派檔案控制代碼的數目
已使用檔案控制代碼的數目
檔案控制代碼的最大數目 ,
單個進程能夠開啟的最大fd數量為 ulimit -n, 可以通過sysconf(_SC_OPEN_MAX)擷取預設的進程fd開啟數量。
修改fd限制可以先修改shell的ulimit -n,
或者通過setrlimit函數進行修改:
void modifyfdlimit()
{
rlimit fdLimit;
fdLimit.rlim_cur = 30000;
fdLimit.rlim_max = 30000;
if (-1 == setrlimit (RLIMIT_NOFILE, &fdLimit))
{
printf ("Set max fd open count fai. /nl");
char cmdBuffer [64];
sprintf (cmdBuffer, "ulimit -n %d", 30000);
if (-1 == system (cmdBuffer))
{
printf("%s failed. /n", cmdBuffer);
exit(0);
}
if (-1 == getrlimit (RLIMIT_NOFILE, &fdLimit))
{
printf("Ulimit fd number failed.");
exit(0);
}
}
//printf("Hard limit: %d. Soft limit: %d", fdLimit.rlim_max, fdLimit.rlim_cur);
}