我在命令行上输入 ulimit -n 并得到 1024 作为答案。
然后我运行以下 java 程序(尝试证明打开文件的限制):
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
public class tester {
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException, Exception{
List list = new ArrayList();
int i = 0;
for (i = 0; i < 5000; i++){
try {
FileInputStream is = new FileInputStream(new File("/tmp/test.txt"));
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
//System.out.println(br.readLine());
list.add(is);
}
catch(Exception e){
System.out.println("Error on run: " + i);
}
}
System.out.println(i);
}
}
当打开 4096 个文件时,文件数量过多,就会引发异常。这个数字不应该是 1024 或更少吗?每个用户的文件限制是每个进程还是每个帐户?(即,无论我运行什么进程,每个用户都不能打开超过 1024 个文件,或者每个进程最多可以打开 1024 个文件。)
谢谢!
答案1
详细阐述 Tink 的评论;
对于现代 Red Hat Enterprise Linux (RHEL) 和类似的 Linux 发行版,/etc/security/limits.conf
定义了文件打开、进程打开和其他此类限制。
' soft
' 限制基本上是所有用户都会收到的“默认”限制。任何 ' hard
' 限制都是内核强制执行的,并且是给定用户的绝对最大值。
我建议你阅读全部任何修改之前对该配置文件的文档
来自 RHEL 5 limits.conf 手册页
hard for enforcing hard resource limits. These limits are set by the
superuser and enforced by the Kernel. The user cannot raise his
requirement of system resources above such values.
soft for enforcing soft resource limits. These limits are ones that the
user can move up or down within the permitted range by any
pre-exisiting hard limits. The values specified with this token can
be thought of as default values, for normal system usage.
- for enforcing both soft and hard resource limits together.
Note, if you specify a type of '-' but neglect to supply the item and
value fields then the module will never enforce any limits on the
specified user/group etc.