DOCUMENT ID: 3379-30
SYNOPSIS: Too many open files thrown when Runtime.exec() is invoked
OS: Solaris/SunOS
PLATFORM: Sparc
OS VERSION: 8
TECH AREA: Java
PRODUCT: JDK
KEYWORDS: IOException, Too many open files
DESCRIPTION:
I have encountered the following exception when I run the following program
using Runtime.exec() on Solaris. How do I fix this problem?
// ========= Exception Information ======
java.io.IOException: Too many open files
at java.lang.UNIXProcess.forkAndExec(Native Method) at
java.lang.UNIXProcess.forkAndExec(Compiled Code) at
java.lang.UNIXProcess.<init>(Compiled Code) at
java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.execInternal(Compiled Code) at
java.lang.Runtime.exec(Compiled Code)
at java.lang.Runtime.exec(Compiled Code)
at java.lang.Runtime.exec(Compiled Code)
at TestPro.run(Compiled Code)
at TestPro.main(TestPro.java:29)
// ========= My Program ============
public class TestPro{
Runtime runtime = null;
Process p = null;
int exitValue = -1;
public TestPro(){
runtime = Runtime.getRuntime();
};
public void run() {
try {
while (true) {
p = runtime.exec("echo");
java.lang.Thread.sleep(1000);
p.waitFor();
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(
String s[]) {
TestPro tp = new TestPro();
tp.run();
}
}
SOLUTION:
* The subprocess is not killed when there are no more references
* to the <code>Process</code> object, but rather the
subprocess
* continues executing asynchronously.
This implies that a Process object can not be finalized. Also there is nothing
in the specification of waitFor() which implies that it is allowed to close the
I/O streams. The java code could read the process's output after it finishes.
Closing the process file descriptors should be done in the user code.
Add the following lines of code after calling p.waitFor();
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
This should allow you to run the
test code indefinitely.
Note that increasing the file descriptor limit in ulimit will only postpone
the occurrence of the problem.
DATE APPROVED: 03/05/01
--------------------------------------------------------------------------------
Copyright (c) 1997 Sun Microsystems, Inc.