Executing shell commands from Java

前端 未结 1 1498
梦谈多话
梦谈多话 2020-12-11 18:10

I\'m trying to execute a shell command from a java application, on the GNU/Linux platform. The problem is that the script, that calls another java application, never ends, a

相关标签:
1条回答
  • 2020-12-11 19:02

    Are you processing the standard input and standard output? From the javadocs:

    Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

    Process cmdProc = Runtime.getRuntime().exec(command);
    
    
    BufferedReader stdoutReader = new BufferedReader(
             new InputStreamReader(cmdProc.getInputStream()));
    String line;
    while ((line = stdoutReader.readLine()) != null) {
       // process procs standard output here
    }
    
    BufferedReader stderrReader = new BufferedReader(
             new InputStreamReader(cmdProc.getErrorStream()));
    while ((line = stderrReader.readLine()) != null) {
       // process procs standard error here
    }
    
    int retValue = cmdProc.exitValue();
    
    0 讨论(0)
提交回复
热议问题