ITeye博客

如何查看节点的可用句柄数目和已用句柄数

mryufeng · 2010-04-08 03:31 · erlang · 编程语言 · Markdown

很多同学在使用erlang的过程中, 碰到了很奇怪的问题, 后来查明都是文件句柄不够用了, 因为系统默认的是每个进程1024. 所以我们有必要在程序运行的时候, 了解这些信息, 以便诊断和预警. 下面的这个程序就演示了这个如何查看节点的可用句柄数目和已用句柄数的功能.

首先确保你已经安装了lsof, 我的系统是ubuntu可以这样安装. root@ubuntu:~# apt-get -y install lsof
root@ubuntu:~# cat fd.erl


-module(fd).
-export([start/0]).

get_total_fd_ulimit() ->
    {MaxFds, _} = string:to_integer(os:cmd("ulimit -n")),
    MaxFds.

get_total_fd() -> get_total_fd(os:type()).

get_total_fd({unix, Os})
  when Os =:= linux orelse
       Os =:= darwin orelse
       Os =:= freebsd orelse Os =:= sunos ->
    get_total_fd_ulimit();
get_total_fd(_) -> unknown.

get_used_fd_lsof() ->
    Lsof = os:cmd("lsof -d \"0-9999999\" -lna -p " ++
                  os:getpid()),
    string:words(Lsof, $\n).

get_used_fd() -> get_used_fd(os:type()).

get_used_fd({unix, Os})
  when Os =:= linux orelse
       Os =:= darwin orelse Os =:= freebsd ->
    get_used_fd_lsof();
get_used_fd(_) -> unknown.

start()->
    io:format("total fd: ~p~n"
              "used fd: ~p~n", [get_total_fd(), get_used_fd()]),
    halt(0).

root@ubuntu:~# erlc fd.erl root@ubuntu:~# ulimit -n 1024 root@ubuntu:~# erl -noshell -s fd
total fd: 1024 used fd: 10 root@ubuntu:~# ulimit -n 10240
root@ubuntu:~# erl -noshell -s fd total fd: 10240 used fd: 10 root@ubuntu:~#

收工!

评论(1)

  1. #1 楼 · hittyo · 2010-04-08 10:56

    貌似有碰到过(win平台),谢谢了

评论功能维护中,当前仅展示历史评论。