TOC

Linux 文件描述符

文件描述符

File Descriptor

“一切皆文件” 设计思想来自早期 Unix,这是现在 Unix/Linux 界的一个非常重要的概念(根据 Plan9 操作系统的相关资料,这一条没有得到彻底的贯彻)。

允许打开的最大文件数

系统限制

cat /proc/sys/fs/file-nr
# 17781 0   9223372036854775807
# 已分配, 已使用, 最大值

cat /proc/sys/fs/file-max
# 9223372036854775807

sudo sysctl -a | grep file
# fs.file-max = 9223372036854775807
# fs.file-nr = 17813    0   9223372036854775807

修改:

echo 100000000 > /proc/sys/fs/file-max
sysctl fs.file-max 100000000

进程限制

# ulimit 是一个 Shell 内建命令
ulimit -a       # 输出所有的相关限制
ulimit -n       # 当前进程的最大打开文件数
ulimit -n 10240 # 修改当前进程的最大打开文件数

ps -ef | grep sshd | grep -Fv 'grep '
root        1080       1  0 10月16 ?      00:00:00 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups
sudo ls -l /proc/`pgrep sshd`/fd
总用量 0
lr-x------ 1 root root 64 10月 17 12:04 0 -> /dev/null
lrwx------ 1 root root 64 10月 17 12:04 1 -> 'socket:[25487]'
lrwx------ 1 root root 64 10月 17 12:04 2 -> 'socket:[25487]'
lrwx------ 1 root root 64 10月 17 12:04 3 -> 'socket:[28674]'
lrwx------ 1 root root 64 10月 17 12:04 4 -> 'socket:[28676]'

/etc/security/limits.conf

echo "* soft nofile 65535" | sudo tee -a /etc/security/limits.conf
echo "* hard nofile 65535" | sudo tee -a /etc/security/limits.conf

系统会根据 /etc/pam.d/login 中的 PAM 配置来为登录用户设置,
如果配置了 session required /lib/security/pam_limits.so, 就会加载 /etc/security/limits.conf 设置用户的各种限制值。

<domain>        <type>  <item>  <value>
  1. domain
  2. a user name
  3. a group name, with @group syntax
  4. the wildcard *, for default entry
  5. the wildcard %, can be also used with %group syntax, for maxlogin limit
  6. NOTE: group and wildcard limits are not applied to root.
    To apply a limit to the root user, must be the literal username root.
  7. type
  8. "soft" for enforcing the soft limits
  9. "hard" for enforcing hard limits
  10. item
  11. core - limits the core file size (KB)
  12. data - max data size (KB)
  13. fsize - maximum filesize (KB)
  14. memlock - max locked-in-memory address space (KB)
  15. nofile - max number of open file descriptors
  16. rss - max resident set size (KB)
  17. stack - max stack size (KB)
  18. cpu - max CPU time (MIN)
  19. nproc - max number of processes
  20. as - address space limit (KB)
  21. maxlogins - max number of logins for this user
  22. maxsyslogins - max number of logins on the system
  23. priority - the priority to run user process with
  24. locks - max number of file locks the user can hold
  25. sigpending - max number of pending signals
  26. msgqueue - max memory used by POSIX message queues (bytes)
  27. nice - max nice priority allowed to raise to values: [-20, 19]
  28. rtprio - max realtime priority
  29. chroot - change root to directory (Debian-specific)