ulimit 查看 Maximum number of open file descriptors

文章目录

    ulimit 的作用

    网上大部分介绍是说,ulimit 显示的是当前用户的资源限制。

    “ulimit” is an interesting Linux shell command that can set or report the resource limit of the current user.

    而 man ulimit 的描述是,shell 的资源限制。

    ulimit builtin sets or outputs the resource usage limits of the shell and any processes spawned by it.

    ulimit 输出

    > ulimit -a
    Maximum size of core files created                           (kB, -c) 0
    Maximum size of a process’s data segment                     (kB, -d) unlimited
    Maximum size of files created by the shell                   (kB, -f) unlimited
    Maximum size that may be locked into memory                  (kB, -l) 64
    Maximum resident set size                                    (kB, -m) unlimited
    Maximum number of open file descriptors                          (-n) 1024
    Maximum stack size                                           (kB, -s) 8192
    Maximum amount of cpu time in seconds                   (seconds, -t) unlimited
    Maximum number of processes available to a single user           (-u) 7823
    Maximum amount of virtual memory available to the shell      (kB, -v) unlimited
    

    其中的 Maximum number of open file descriptors 即是最大文件描述符数量。其数值与下面命令的返回值一样:

    ulimit -n

    代表每个进程的 open file descriptors 限制,即当前会话 / 进程打开文件句柄数。

    什么是 file descriptor

    当你打开一个文件,操作系统会创建一条记录,用来表示这个打开的文件,并存储一些相关的信息。
    所以,如果打开 100 个文件,就会有 100 条这样的记录。
    每条记录有一个类似数据库的主键 ID 这样的标识,即非零整数。这就是 file descriptor。

    当年打开一个 Network Socket,也会产生一个这样的非零整数描述符,称之为 socket descriptor。
    通常说的 file descriptor 包含 socket descriptor。

    In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files. Every File has an associated number called File Descriptor (FD).

    查看系统级限制

    ulimit -n 是单个进程的限制,如果要看整个系统的限制数:

    > cat /proc/sys/fs/file-max
    1048576
    

    查看当前已打开的 FD 总数

    直接通过 lsof 的结果进行计数是不准确的,因为很多进程会重复使用相同的文件。
    所以需要去重:

    > lsof | wc -l
    565
    > lsof|awk '{print $9}'|sort|uniq|wc -l
    64
    

    查看指定进程打开的 FD 列表

    lsof - list open files

    lsof -a -p <PID>
    

    只查看网络 FD:

    lsof -i -a -p <PID>
    

    参考

    • https://linuxhint.com/linux_ulimit_command/
    • https://stackoverflow.com/questions/5256599/what-are-file-descriptors-explained-in-simple-terms
    • https://unix.stackexchange.com/questions/36841/why-is-number-of-open-files-limited-in-linux
    • https://unix.stackexchange.com/questions/333186/how-to-list-the-open-file-descriptors-and-the-files-they-refer-to-in-my-curren

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式