1. 程式人生 > >Linux問題 open too many files

Linux問題 open too many files

部署到linux下的tomcat,今天發現包了“java.net.SocketException: Too many open files”,以前從來沒有遇到過,在此記錄一下:

徹底解決問題的是第三步, 所以,可以直接跳到第三步去看解決方法和步驟,當日第一、第二步是我不斷探索,嘗試解決問題的過程,雖然沒有找到點上,但是還是有些意義的,因為linux切實有開啟資源數量的限制,肯定需要修改的。

異常資訊:

Java程式碼 複製程式碼 收藏程式碼
  1. ............   
  2. Oct 1720115:22:41 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run   
  3. SEVERE: Socket accept failed   
  4. java.net.SocketException: Too many open files   
  5.         at java.net.PlainSocketImpl.socketAccept(Native Method)   
  6.         at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)   
  7.         at java.net.ServerSocket.implAccept(ServerSocket.java:470)   
  8.         at java.net.ServerSocket.accept(ServerSocket.java:438)   
  9.         at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:
    59)   
  10.         at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)   
  11.         at java.lang.Thread.run(Thread.java:636)   
  12. Oct 1720115:22:43 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run   
  13. SEVERE: Socket accept failed   
  14. java.net.SocketException: Too many open files   
  15.         at java.net.PlainSocketImpl.socketAccept(Native Method)   
  16.         at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)   
  17.         at java.net.ServerSocket.implAccept(ServerSocket.java:470)   
  18.         at java.net.ServerSocket.accept(ServerSocket.java:438)   
  19.         at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)   
  20.         at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)   
  21.         at java.lang.Thread.run(Thread.java:636)   
  22. Oct 1720115:22:44 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run   
  23. SEVERE: Socket accept failed   
  24. java.net.SocketException: Too many open files   
  25.         at java.net.PlainSocketImpl.socketAccept(Native Method)   
  26.         at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)   
  27.         at java.net.ServerSocket.implAccept(ServerSocket.java:470)   
  28.         at java.net.ServerSocket.accept(ServerSocket.java:438)   
  29.         at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)   
  30.         at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)   
  31.         at java.lang.Thread.run(Thread.java:636)   
  32. ............  
............
Oct 17, 2011 5:22:41 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run
SEVERE: Socket accept failed
java.net.SocketException: Too many open files
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)
        at java.net.ServerSocket.implAccept(ServerSocket.java:470)
        at java.net.ServerSocket.accept(ServerSocket.java:438)
        at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)
        at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)
        at java.lang.Thread.run(Thread.java:636)
Oct 17, 2011 5:22:43 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run
SEVERE: Socket accept failed
java.net.SocketException: Too many open files
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)
        at java.net.ServerSocket.implAccept(ServerSocket.java:470)
        at java.net.ServerSocket.accept(ServerSocket.java:438)
        at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)
        at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)
        at java.lang.Thread.run(Thread.java:636)
Oct 17, 2011 5:22:44 PM org.apache.tomcat.util.net.JIoEndpoint$Acceptor run
SEVERE: Socket accept failed
java.net.SocketException: Too many open files
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:375)
        at java.net.ServerSocket.implAccept(ServerSocket.java:470)
        at java.net.ServerSocket.accept(ServerSocket.java:438)
        at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:59)
        at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:210)
        at java.lang.Thread.run(Thread.java:636)
............

原因:
   linux下有有檔案限制,結果檔案數操作最大限制,導致程式異常:問題是程式中有個靜態方法開啟檔案時忘記關閉。兩種解決方法,一是設定linux的最大檔案開啟數量(無法根本解決問題),二是解決程式中的bugs,即消除有問題的程式碼。

第一次解決
解決:
方法一、增大系統開啟檔案的數量(無法根本解決問題)、
   1、預設linux同時最大開啟檔案數量為1024個,用命令檢視如下:ulimit -a:檢視系統上受限資源的設定(open files (-n) 1024):

Java程式碼 複製程式碼 收藏程式碼
  1. [[email protected]**** bin]# ulimit -a   
  2. core file size          (blocks, -c) 0
  3. data seg size           (kbytes, -d) unlimited   
  4. scheduling priority             (-e) 0
  5. file size               (blocks, -f) unlimited   
  6. pending signals                 (-i) 16384
  7. max locked memory       (kbytes, -l) 32
  8. max memory size         (kbytes, -m) unlimited   
  9. open files                      (-n) 1024
  10. pipe size            (512 bytes, -p) 8
  11. POSIX message queues     (bytes, -q) 819200
  12. real-time priority              (-r) 0
  13. stack size              (kbytes, -s) 10240
  14. cpu time               (seconds, -t) unlimited   
  15. max user processes              (-u) 16384
  16. virtual memory          (kbytes, -v) unlimited   
  17. file locks                      (-x) unlimited   
  18. [[email protected]**** bin]#  
[[email protected]**** bin]# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 16384
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 16384
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
[[email protected]**** bin]#

2、可以修改同時開啟檔案的最大數基本可以解決:ulimit -n 4096

Java程式碼 複製程式碼 收藏程式碼
  1. [[email protected]**** bin]# ulimit -n 4096
  2. [[email protected]**** bin]# ulimit -a   
  3. core file size          (blocks, -c) 0
  4. data seg size           (kbytes, -d) unlimited   
  5. scheduling priority             (-e) 0
  6. file size               (blocks, -f) unlimited   
  7. pending signals                 (-i) 16384
  8. max locked memory       (kbytes, -l) 32
  9. max memory size         (kbytes, -m) unlimited   
  10. open files                      (-n) 4096
  11. pipe size            (512 bytes, -p) 8
  12. POSIX message queues     (bytes, -q) 819200
  13. real-time priority              (-r) 0
  14. stack size              (kbytes, -s) 10240
  15. cpu time               (seconds, -t) unlimited   
  16. max user processes              (-u) 16384
  17. virtual memory          (kbytes, -v) unlimited   
  18. file locks                      (-x) unlimited   
  19. [[email protected]**** bin]#  
[[email protected]**** bin]# ulimit -n 4096
[[email protected]**** bin]# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 16384
max locked memory       (kbytes, -l) 32
max memory size         (kbytes, -m) unlimited
open files                      (-n) 4096
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 16384
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
[[email protected]**** bin]#


已經修改了最大開啟檔案數。

方法二、修改程式中的bugs:
程式中有個靜態的方法開啟檔案後,沒有關閉檔案,導致每次請求都會去開啟檔案,在程式中填入關閉輸入流的操作即可以:
Java程式碼 複製程式碼 收藏程式碼
  1. publicstatic List<GpsPoint> getArrayList() throws IOException {   
  2.         List<GpsPoint> pointList = null;   
  3. // 讀取配置檔案
  4.         InputStream in = ParseGpsFile.class.getClassLoader().getResourceAsStream("GPS1.TXT");   
  5. // 讀路徑出錯,換另一種方式讀取配置檔案
  6. if (null == in) {   
  7.             System.out.println("讀取檔案失敗");   
  8. return pointList;   
  9.         }   
  10.         pointList = new ArrayList<GpsPoint>();   
  11. try {   
  12.             BufferedReader br = new BufferedReader(new InputStreamReader(in));   
  13.             String longtude = "";   
  14.             String latude = "";   
  15.             String elevation = "";   
  16. while ((longtude = br.readLine()) != null) {   
  17. // 讀下一行資料,讀緯度
  18.                 latude = br.readLine();   
  19. if (null == latude) {   
  20. // 退出迴圈
  21. break;   
  22.                 }   
  23. // 讀下一行資料,讀海拔
  24.                 elevation = br.readLine();   
  25. if (null == latude) {   
  26. // 退出迴圈
  27. break;   
  28.                 }   
  29. // 加入一個點
  30.                 pointList.add(gps2point(longtude, latude, elevation));   
  31.             }   
  32.             in.close();   
  33.             System.out.println("\n\n");   
  34.         } catch (Exception e) {   
  35.             in.close();   
  36.             e.printStackTrace();   
  37.         }   
  38. return pointList;   
  39.     }  
public static List<GpsPoint> getArrayList() throws IOException {

        List<GpsPoint> pointList = null;
        // 讀取配置檔案
        InputStream in = ParseGpsFile.class.getClassLoader().getResourceAsStream("GPS1.TXT");
        
        // 讀路徑出錯,換另一種方式讀取配置檔案
        if (null == in) {
            
            System.out.println("讀取檔案失敗");
            
            return pointList;
        }
        
        pointList = new ArrayList<GpsPoint>();
        
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String longtude = "";
            String latude = "";
            String elevation = "";
            while ((longtude = br.readLine()) != null) {
                
                // 讀下一行資料,讀緯度
                latude = br.readLine();
                
                if (null == latude) {
                    
                    // 退出迴圈
                    break;
                }
                
                // 讀下一行資料,讀海拔
                elevation = br.readLine();
                if (null == latude) {
                    
                    // 退出迴圈
                    break;
                }
                
                // 加入一個點
                pointList.add(gps2point(longtude, latude, elevation));
            }
            
            in.close();
            System.out.println("\n\n");
        } catch (Exception e) {
            
            in.close();
            e.printStackTrace();
        }
        
        return pointList;
    }


問題徹底解決

-----
第二次解決:
實際測試後發現這個問題還沒有解決,最終又找了些方法,經過一段時間的測試,似乎解決了問題:

具體步驟如下:
linux為redhat伺服器版本(非個人版),必須設定的內容:

1、/etc/pam.d/login 新增
Java程式碼 複製程式碼 收藏程式碼
  1. session required     /lib/security/pam_limits.so  
session required     /lib/security/pam_limits.so

# 注意看這個檔案的註釋
具體檔案的內容為:
Java程式碼 複製程式碼 收藏程式碼
  1. [[email protected]**** ~]# vi /etc/pam.d/login   
  2. #%PAM-1.0
  3. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so   
  4. auth       include      system-auth   
  5. account    required     pam_nologin.so   
  6. account    include      system-auth   
  7. password   include      system-auth   
  8. # pam_selinux.so close should be the first session rule   
  9. session    required     pam_selinux.so close   
  10. session    optional     pam_keyinit.so force revoke   
  11. session    required     pam_loginuid.so   
  12. session    include      system-auth   
  13. session    optional     pam_console.so   
  14. # pam_selinux.so open should only be followed by sessions to be executed in the user context   
  15. session    required     pam_selinux.so open   
  16. ~   
  17. "/etc/pam.d/login" 15L, 644C  
[[email protected]**** ~]# vi /etc/pam.d/login
#%PAM-1.0
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
auth       include      system-auth
account    required     pam_nologin.so
account    include      system-auth
password   include      system-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    optional     pam_keyinit.so force revoke
session    required     pam_loginuid.so
session    include      system-auth
session    optional     pam_console.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open

~
"/etc/pam.d/login" 15L, 644C


修改後的內容:

Java程式碼 複製程式碼 收藏程式碼
  1. -bash: [[email protected]****: command not found   
  2. [[email protected]**** ~]# clear   
  3. [[email protected]**** ~]# cat /etc/pam.d/login   
  4. #%PAM-1.0
  5. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so   
  6. auth       include      system-auth   
  7. account    required     pam_nologin.so   
  8. account    include      system-auth   
  9. password   include      system-auth   
  10. # pam_selinux.so close should be the first session rule   
  11. session    required     pam_selinux.so close   
  12. session    optional     pam_keyinit.so force revoke   
  13. session    required     pam_loginuid.so   
  14. session    include      system-auth   
  15. session    optional     pam_console.so   
  16. # pam_selinux.so open should only be followed by sessions to be executed in the user context   
  17. session    required     pam_selinux.so open   
  18. # kevin.xie added, fixed 'too many open file' bug, limit open max files 10242011-10-24
  19. session required     /lib/security/pam_limits.so   
  20. [[email protected]**** ~]#  
-bash: [[email protected]****: command not found
[[email protected]**** ~]# clear
[[email protected]**** ~]# cat /etc/pam.d/login
#%PAM-1.0
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
auth       include      system-auth
account    required     pam_nologin.so
account    include      system-auth
password   include      system-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    optional     pam_keyinit.so force revoke
session    required     pam_loginuid.so
session    include      system-auth
session    optional     pam_console.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open
# kevin.xie added, fixed 'too many open file' bug, limit open max files 1024, 2011-10-24
session required     /lib/security/pam_limits.so

[[email protected]**** ~]#


2. /etc/security/limits.conf 新增
Java程式碼 複製程式碼 收藏程式碼
  1. root          –    nofile       1006154
root          –    nofile       1006154

root 是一個使用者,如果是想所有使用者生效的話換成 * ,設定的數值與硬體配置有關,別設定太大了。
修改前內容
Java程式碼 複製程式碼 收藏程式碼
  1. [[email protected]**** ~]# cat /etc/security/limits.conf   
  2. # /etc/security/limits.conf   
  3. #   
  4. #Each line describes a limit for a user in the form:   
  5. #   
  6. #<domain>        <type>  <item>  <value>   
  7. #   
  8. #Where:   
  9. #<domain> can be:   
  10. #        - an user name   
  11. #        - a group name, with @group syntax   
  12. #        - the wildcard *, fordefault entry   
  13. #        - the wildcard %, can be also used with %group syntax,   
  14. #                 for maxlogin limit   
  15. #   
  16. #<type> can have the two values:   
  17. #        - "soft"for enforcing the soft limits   
  18. #        - "hard"for enforcing hard limits   
  19. #   
  20. #<item> can be one of the following:   
  21. #        - core - limits the core file size (KB)   
  22. #        - data - max data size (KB)   
  23. #        - fsize - maximum filesize (KB)   
  24. #        - memlock - max locked-in-memory address space (KB)   
  25. #        - nofile - max number of open files   
  26. #        - rss - max resident set size (KB)   
  27. #        - stack - max stack size (KB)   
  28. #        - cpu - max CPU time (MIN)   
  29. #        - nproc - max number of processes   
  30. #        - as - address space limit   
  31. #        - maxlogins - max number of logins forthis user   
  32. #        - maxsyslogins - max number of logins on the system   
  33. #        - priority - the priority to run user process with   
  34. #        - locks - max number of file locks the user can hold   
  35. #        - sigpending - max number of pending signals   
  36. #        - msgqueue - max memory used by POSIX message queues (bytes)   
  37. #        - nice - max nice priority allowed to raise to   
  38. #        - rtprio - max realtime priority   
  39. #   
  40. #<domain>      <type>  <item>         <value>   
  41. #   
  42. #*               soft    core            0
  43. #*               hard    rss             10000
  44. #@student        hard    nproc           20
  45. #@faculty        soft    nproc           20
  46. #@faculty        hard    nproc           50
  47. #ftp             hard    nproc           0
  48. #@student        -       maxlogins       4
  49. # End of file   
  50. [[email protected]**** ~]#   
  51. [[email protected]**** ~]# cat /etc/security/limits.conf   
  52. # /etc/security/limits.conf   
  53. #   
  54. #Each line describes a limit for a user in the form:   
  55. #   
  56. #<domain>        <type>  <item>  <value>   
  57. #   
  58. #Where:   
  59. #<domain> can be:   
  60. #        - an user name   
  61. #        - a group name, with @group syntax   
  62. #        - the wildcard *, fordefault entry   
  63. #        - the wildcard %, can be also used with %group syntax,   
  64. #                 for maxlogin limit   
  65. #   
  66. #<type> can have the two values:   
  67. #        - "soft"for enforcing the soft limits   
  68. #        - "hard"for enforcing hard limits   
  69. #   
  70. #<item> can be one of the following:   
  71. #        - core - limits the core file size (KB)   
  72. #        - data - max data size (KB)   
  73. #        - fsize - maximum filesize (KB)   
  74. #        - memlock - max locked-in-memory address space (KB)   
  75. #        - nofile - max number of open files   
  76. #        - rss - max resident set size (KB)   
  77. #        - stack - max stack size (KB)   
  78. #        - cpu - max CPU time (MIN)   
  79. #        - nproc - max number of processes   
  80. #        - as - address space limit   
  81. #        - maxlogins - max number of logins forthis user   
  82. #        - maxsyslogins - max number of logins on the system   
  83. #        - priority - the priority to run user process with   
  84. #        - locks - max number of file locks the user can hold   
  85. #        - sigpending - max number of pending signals   
  86. #        - msgqueue - max memory used by POSIX message queues (bytes)   
  87. #        - nice - max nice priority allowed to raise to   
  88. #        - rtprio - max realtime priority   
  89. #   
  90. #<domain>      <type>  <item>         <value>   
  91. #   
  92. #*               soft    core            0
  93. #*               hard    rss             10000
  94. #@student        hard    nproc           20
  95. #@faculty        soft    nproc           20
  96. #@faculty        hard    nproc           50
  97. #ftp             hard    nproc           0
  98. #@student        -       maxlogins       4
  99. # kevin.xie added, fixed 'too many open file' bug, limit open max files 10242011-10-24
  100. * - nofile 102400
  101. # End of file   
  102. [[email protected]**** ~]#  
[[email protected]**** ~]# cat /etc/security/limits.conf
# /etc/security/limits.conf
#
#Each line describes a limit for a user in the form:
#
#<domain>        <type>  <item>  <value>
#
#Where:
#<domain> can be:
#        - an user name
#        - a group name, with @group syntax
#        - the wildcard *, for default entry
#        - the wildcard %, can be also used with %group syntax,
#                 for maxlogin limit
#
#<type> can have the two values:
#        - "soft" for enforcing the soft limits
#        - "hard" for enforcing hard limits
#
#<item> can be one of the following:
#        - core - limits the core file size (KB)
#        - data - max data size (KB)
#        - fsize - maximum filesize (KB)
#        - memlock - max locked-in-memory address space (KB)
#        - nofile - max number of open files
#        - rss - max resident set size (KB)
#        - stack - max stack size (KB)
#        - cpu - max CPU time (MIN)
#        - nproc - max number of processes
#        - as - address space limit
#        - maxlogins - max number of logins for this user
#        - maxsyslogins - max number of logins on the system
#        - priority - the priority to run user process with
#        - locks - max number of file locks the user can hold
#        - sigpending - max number of pending signals
#        - msgqueue - max memory used by POSIX message queues (bytes)
#        - nice - max nice priority allowed to raise to
#        - rtprio - max realtime priority
#
#<domain>      <type>  <item>         <value>
#

#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4

# End of file
[[email protected]**** ~]#
[[email protected]**** ~]# cat /etc/security/limits.conf
# /etc/security/limits.conf
#
#Each line describes a limit for a user in the form:
#
#<domain>        <type>  <item>  <value>
#
#Where:
#<domain> can be:
#        - an user name
#        - a group name, with @group syntax
#        - the wildcard *, for default entry
#        - the wildcard %, can be also used with %group syntax,
#                 for maxlogin limit
#
#<type> can have the two values:
#        - "soft" for enforcing the soft limits
#        - "hard" for enforcing hard limits
#
#<item> can be one of the following:
#        - core - limits the core file size (KB)
#        - data - max data size (KB)
#        - fsize - maximum filesize (KB)
#        - memlock - max locked-in-memory address space (KB)
#        - nofile - max number of open files
#        - rss - max resident set size (KB)
#        - stack - max stack size (KB)
#        - cpu - max CPU time (MIN)
#        - nproc - max number of processes
#        - as - address space limit
#        - maxlogins - max number of logins for this user
#        - maxsyslogins - max number of logins on the system
#        - priority - the priority to run user process with
#        - locks - max number of file locks the user can hold
#        - sigpending - max number of pending signals
#        - msgqueue - max memory used by POSIX message queues (bytes)
#        - nice - max nice priority allowed to raise to
#        - rtprio - max realtime priority
#
#<domain>      <type>  <item>         <value>
#

#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4
# kevin.xie added, fixed 'too many open file' bug, limit open max files 1024, 2011-10-24
* - nofile 102400

# End of file
[[email protected]**** ~]#


修改後的內容
Java程式碼 複製程式碼 收藏程式碼 3. 修改 /etc/rc.local   新增 Java程式碼 複製程式碼 收藏程式碼
  1. echo 8061540 > /proc/sys/fs/file-max  

修改前內容
Java程式碼 複製程式碼 收藏程式碼
  1. [[email protected]**** ~]# cat /proc/sys/fs/file-max   
  2. 4096
  3. [[email protected]**** ~]#  
[[email protected]**** ~]# cat /proc/sys/fs/file-max
4096
[[email protected]**** ~]#


修改後內容
Java程式碼 複製程式碼 收藏程式碼
  1. [[email protected]**** ~]# cat /proc/sys/fs/file-max   
  2. 4096000
  3. [[email protected]**** ~]#  
[[email protected]**** ~]# cat /proc/sys/fs/file-max
4096000
[[email protected]**** ~]#


做完3個步驟,就可以了。


**************************************
補充說明:
/proc/sys/fs/file-max
該檔案指定了可以分配的檔案控制代碼的最大數目。如果使用者得到的錯誤訊息宣告由於開啟檔案數已經達到了最大值,從而他們不能開啟更多檔案,則可能需要增加該值。可將這個值設定成有任意多個檔案,並且能通過將一個新數字值寫入該檔案來更改該值。
預設設定:4096
/proc/sys/fs/file-nr
該檔案與 file-max 相關,它有三個值:
已分配檔案控制代碼的數目
已使用檔案控制代碼的數目
檔案控制代碼的最大數目
該檔案是隻讀的,僅用於顯示資訊。
關於“開啟檔案數”限制
Linux系統上對每一個使用者可使用的系統資源都是有限制的,這是多使用者系統必然要採用的一種資源管理手段,試想假如沒有這種機制,那麼任何一個普通使用者寫一個死迴圈程式,用不了多久系統就要“拒絕服務”了。
今天我遇到了tomcat日誌報的錯誤資訊”too many open files”,第一意識就想到了是ulimit控制的”open files“限制。然而問題來了。我在/etc/profile里加入了 ulimit -n 4096儲存之後,普通使用者登入的時候均會收到一條錯誤資訊ulimit: open files: cannot modify limit: Operation not permitted。然後普通使用者的open files限制還是預設值1024。
然後開始在網際網路上搜索關於ulimit的資訊。網際網路果然方便,資訊鋪天蓋地。大家也可以搜一下試一下。其中我瞭解到兩個以前不知道的相關內容。
第一個是核心引數 fs.file-max  ,影射為 /proc/sys/fs/file-max
第二個是配置檔案 /etc/security/limits.conf
其中大部分的資訊中提到 將 /proc/sys/fs/file-max的值設定為4096和ulimit -n 4096是相同的效果。對此我很懷疑,為什麼呢?首先ulimit 是一個普通使用者也可以使用的命令,而fs.file-max只有root有權設定。其次,很明顯fs.file-max是一個全域性的設定,而ulimit 是一個區域性的設定,很明顯的是不相同的。
帶著疑慮,又在網上搜索了許久,未果(實際上是我搜索的關鍵字不夠準確)。
最後終於在核心文件/usr/src/linux/Documentation/sysctl/fs.txt裡找到下面一段話:
file-max & file-nr:
The kernel allocates file handles dynamically, but as yet it doesn’t free them again. The value in file-max denotes the maximum number of file-handles that the Linux kernel will allocate. When you get lots of error messages about running out of file handles, you might want to increase this limit.
The three values in file-nr denote the number of allocated file handles, the number of unused file handles and the maximum number of file handles. When the allocated file handles come close to the maximum, but the number of unused file handles is significantly greater than 0, you’ve encountered a peak in your usage of file handles and you don’t need to increase the maximum.
這兩段話的大致意思是:
核心動態地分配和釋放“file handles”(控制代碼)。file-max的值是核心所能分配到的最大控制代碼數。當你收到大量關於控制代碼用完的錯誤資訊時,你可以需要增加這個值以打破老的限制。
file-nr中的三個值的含意分別是:系統已經分配出去(正在使用)的控制代碼數,沒有用到的控制代碼數和所有分配到的最大控制代碼數。當分配出去的控制代碼數接近 最大控制代碼數,而“無用的控制代碼數”大於零時,表明你遇到了一個“控制代碼”使用高峰,這意為著你不需要增加file-max的值。
看完這段話,相信大家都明白了。file-max是系統全域性的可用控制代碼數。根據我後來又翻查的資訊,以及對多個系統的檢視求證,這個引數的預設值是跟記憶體大小有關係的,增加實體記憶體以後重啟機器,這個值會增大。大約1G記憶體10萬個控制代碼的線性關係。
再回過頭來看這兩段話,不知道你意識到了沒有,文中只提到了file-max的增加,而沒有提到了該值的減少。那些在操作ulimit時同時操 作了file-max的哥們兒,估計無一例外地將file-max設定成了4096或者2048。但以似乎也沒有因此而導致系統無法開啟檔案或者建議連 接。(實際上,我將file-max的值裝置成256,然後使用shell編寫用vi開啟500個檔案角本執行,並沒有得到任何錯誤資訊,檢視file- nr的值,系統當前分配的控制代碼值已經遠超過了後面的最大值。所以我猜想對於file-max的任何減少的操作都是毫無意義的,姑且不去管他。實踐中需要減 少file-max的時候總是不多見的。 )實事證明我犯了一個致命的錯誤。我測試的時候使用的是root使用者,而當我再次使用普通使用者測試的時候,預料中的錯誤資訊出現了:”Too many open files in system”。可見,file-max的減少對系統也是影響力的。前面的結論“所以我猜想對於file-max的任何減少的操作都是毫無意義的”是錯誤 的。
然後便是/etc/security/limits.conf檔案,這個檔案很簡單,一看就能明白。
於是我按照註釋中描述的格式兩個兩行:
*  soft  nofile  4096
*  hard  nofile  4096
恐怖的是,網上居然有人說改了這個設定是需要重啟系統的!實在是讓人想不通啊,鼎鼎大名的UNIX系統,怎麼可能因為這麼小小的一個改動就需要 重啟系統呢?結果當我再次以普通使用者登入的時候,那個”ulimit: open files: cannot modify limit: Operation not permitted”提示沒有了,檢視ulimit -n,果然已經變成了4096。
linux lsof 修改控制代碼限制(轉)
在Linux下,我們使用ulimit -n 命令可以看到單個程序能夠開啟的最大檔案控制代碼數量(socket連線也算在裡面)。系統預設值1024。
對於一般的應用來說(象Apache、系統程序)1024完全足夠使用。但是如何象squid、mysql、java等單程序處理大量請求的應用來說就有點捉襟見肘了。如果單個程序開啟的檔案控制代碼數量超過了系統定義的值,就會提到“too many files open”的錯誤提示。如何知道當前程序打開了多少個檔案控制代碼呢?下面一段小指令碼可以幫你檢視:
lsof -n |awk ‘{print $2}’|sort|uniq -c |sort -nr|more
在系統訪問高峰時間以root使用者執行上面的指令碼,可能出現的結果如下:
# lsof -n|awk ‘{print $2}’|sort|uniq -c |sort -nr|more
131 24204
57 24244
57 24231
56 24264
其中第一行是開啟的檔案控制代碼數量,第二行是程序號。得到程序號後,我們可以通過ps命令得到程序的詳細內容。
ps -aef|grep 24204
mysql 24204 24162 99 16:15 ? 00:24:25 /usr/sbin/mysqld
哦,原來是mysql程序開啟最多檔案控制代碼數量。但是他目前只打開了131個檔案控制代碼數量,遠遠底於系統預設值1024。
但是如果系統併發特別大,尤其是squid伺服器,很有可能會超過1024。這時候就必須要調整系統引數,以適應應用變化。Linux有硬性限制和軟性限制。可以通過ulimit來設定這兩個引數。方法如下,以root使用者執行以下命令:
ulimit -HSn 4096
以上命令中,H指定了硬性大小,S指定了軟性大小,n表示設定單個程序最大的開啟檔案控制代碼數量。個人覺得最好不要超過4096,畢竟開啟的檔案控制代碼數越多響應時間肯定會越慢。設定控制代碼數量後,系統重啟後,又會恢復預設值。如果想永久儲存下來,可以修改.bash_profile檔案,可以修改 /etc/profile 把上面命令加到最後。



仍未處理的問題:
為什麼redhat9的個人版按照以上的方式修改1024tcp連線限制依然不行呢?
是因為個人版最多支援1024個tcp連線,還是修改方式、相關檔案會有所不同?

以上內容,來源網路並加自己親自測試,經過測試,似乎沒有再出現過問題,但不知道是否真的解決,有待更長時間的測試看看

第三次解決--還解決不了,就徹底無語了(經過壓力測試,執行7天再也沒有出現該問題)
問題的原因是
:原來的MINA2程式之關了IoSession,並沒有關閉IoConnector例項,但恰恰就是因為沒有關閉每次開啟的IoConnector例項,造成了"Too many open files ".
原來的程式:
Java程式碼 複製程式碼 收藏程式碼
  1. /**   
  2.      * <pre><b>功能描述:</b>獲取非同步的session例項。   
  3.      *    
  4.      * @author :Kevin.xie   
  5.      * <b>建立日期 :</b>2011-9-15 上午10:06:27   
  6.      *   
  7.      * @return   
  8.      *   
  9.      * <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)   
  10.      *   
  11.      * </pre>   
  12.      */
  13. publicstatic IoSession getSession1() {     
  14. // 建立客戶端聯結器  
  15.         IoConnector connector = new NioSocketConnector();     
  16. // 設定事件處理器  
  17.         connector.setHandler(new WebClientHandler());     
  18. // 設定編碼過濾器和按行讀取資料模式  
  19.         connector.getFilterChain()     
  20.                 .addLast("codec"new ProtocolCodecFilter(new ObdDemuxingProtocolCodecFactory(false)));     
  21. // 建立連線  
  22.         ConnectFuture future = connector.connect(new InetSocketAddress(ServerConfigBoundle.getServerIp(),     
  23.                 ServerConfigBoundle.getServerPort()));     
  24. // 等待連線建立完成  
  25.         future.awaitUninterruptibly();     
  26. // 獲取連線會話  
  27.         IoSession session = future.getSession();     
  28. return session;     
  29.     }     
  30. /**   
  31.      * <pre><b>功能描述:</b>必須要關閉Connector和IoSession  
  32.      * @author :Kevin.xie   
  33.      * <b>建立日期 :</b>2011-10-20 上午10:20:54   
  34.      *   
  35.      * @param session 要關閉的session   
  36.      *   
  37.      * <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)   
  38.      *   <