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

Lou*_*uis 9 java processbuilder java-io

我继承了一些代码:

Process p = new ProcessBuilder("/bin/chmod", "777", path).start();
p.waitFor();
Run Code Online (Sandbox Code Playgroud)

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

但是,我留下了一堆IO异常:

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

Vin*_*jip 14

我假设你在循环中运行这些chmod命令 - 否则我不明白为什么你会得到这么多例外.您可能因为没有读取生成进程的输出而遇到死锁.这当然用来咬我回到前ProcessBuilder,Runtime.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
} 
Run Code Online (Sandbox Code Playgroud)

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


Lou*_*uis 6

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

使用您的(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);
  }
}
Run Code Online (Sandbox Code Playgroud)

从John B Mathews的帖子中得到了这个想法.