Process Builder waitFor()问题和打开文件限制

我inheritance了一些代码:

Process p = new ProcessBuilder("/bin/chmod", "777", path).start(); p.waitFor(); 

基本上,存在一些古老且高度基于巫术的原因,用于将键/值对作为文件存储在磁盘上。 我真的不想进入它。

但是,我留下了一堆IOexception:

 Exception :Cannot run program "/bin/chmod": java.io.IOException: error=24, Too many open files Message: Cannot run program "/bin/chmod": java.io.IOException: error=24, Too many open files 

一堆我的意思是在1万亿的领域

我感觉waitFor调用是阻止这些进程等待进程完成它并退出,但我认为chmod在文件实际关闭之前返回结果。 有谁知道这是否是这些例外的原因?

我的另一个倾向是数千个文件的打开和关闭在java端没有快速发生,并且还有其他事情发生,可能是某种forms的文件缓冲区在没有被清除时正在调用fw.close()。

我对java很新,这是一个让我难过的地狱奇怪的东西。 (很高兴应用程序仍以某种方式运行..吐出一个非常大的日志文件后)

任何人都可以想办法解决这个问题,清除缓冲区或增加文件打开限制,以便jvm可以跟上自己(假设这是问题)

我假设你在循环中运行这些chmod命令 – 否则我不明白为什么你会得到这么多例外。 您可能会遇到死锁,因为您没有读取生成的进程的输出。 这当然曾经让我回到前ProcessBuilderRuntime.exec()天。

将您的代码段更改为上述模式:

 try { ProcessBuilder pb = new ProcessBuilder("/bin/chmod", "777", path); pb.redirectErrorStream(true); // merge stdout, stderr of process Process p = pb.start(); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader br = new BufferedReader(isr); String lineRead; while ((lineRead = br.readLine()) != null) { // swallow the line, or print it out - System.out.println(lineRead); } int rc = p.waitFor(); // TODO error handling for non-zero rc } catch (IOException e) { e.printStackTrace(); // or log it, or otherwise handle it } catch (InterruptedException ie) { ie.printStackTrace(); // or log it, or otherwise handle it } 

(信用: 这个网站 ),看看是否有助于这种情况。

感谢帮助人员,这应该解决其他地方因此而产生的一些奇怪现象。

使用您的(Vinay)示例和流关闭:

 try{ fw.close(); ProcessBuilder pb = new ProcessBuilder("/bin/chmod", "777", path); pb.redirectErrorStream(true); // merge stdout, stderr of process p = pb.start(); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader br = new BufferedReader(isr); String lineRead; while ((lineRead = br.readLine()) != null) { // swallow the line, or print it out - System.out.println(lineRead); } } catch (Exception ioe) { Logger.logException(Logger.WARN, ioe.getMessage(), ioe); } finally { try { p.waitFor();//here as there is some snipped code that was causing a different // exception which stopped it from getting processed //missing these was causing the mass amounts of open 'files' p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } catch (Exception ioe) { Logger.logException(Logger.WARN, ioe.getMessage(), ioe); } } 

从John B Mathews的post中得到了这个想法。

如果不关闭文件,该过程似乎不太可能完成。 这可能发生在非常大的线程中吗? 或者也许其中一些实际上没有完成(即,它在某些情况下挂在waitFor)?

否则,我认为你将不得不增加打开文件限制。 假设这是一个类Unix系统,“ulimit”命令可能正是你要找的。

如果您正在使用JAVA 6,您还可以在File对象上尝试新的setter(用于读取,写入,执行)。 可能会慢,但它应该工作。