Java Runtime.exec()

后端 未结 3 2044
情话喂你
情话喂你 2020-11-27 07:02

I can run this command from the command line without any problem (the validation script executes):

c:/Python27/python ../feedvalidator/feedvalidator/src/demo         


        
相关标签:
3条回答
  • 2020-11-27 07:25

    You need to drain the output and error streams of the process, or else it will block when the executed program produces output.

    From the Process documentation:

    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.

    0 讨论(0)
  • 2020-11-27 07:39

    Read (and close) p.getInputStream() and p.getErrorStream().

    For example:

    // com.google.common.io.CharStreams
    CharStreams.toString(new InputStreamReader(p.getInputStream()));
    CharStreams.toString(new InputStreamReader(p.getErrorStream()));
    
    0 讨论(0)
  • 2020-11-27 07:44

    People usually got caught by exec routine hangs in Java. I was cought by that once too. The problem is that the process you are trying to execute may (depending on lot of things) either first write to stdOut or stdErr. If you handle them in wrong order exec will hang. To handle this properly always you must create 2 threads to read stdErr and stdOut simulteneously. Sth like:

    Process proc = Runtime.getRuntime().exec( cmd );
    
    // handle process' stdout stream
    Thread out = new StreamHandlerThread( stdOut, proc.getInputStream() );
    out.start();
    
    // handle process' stderr stream
    Thread err = new StreamHandlerThread( stdErr, proc.getErrorStream() );
    err.start();
    
    exitVal = proc.waitFor(); // InterruptedException
    
    ...
    
    out.join();
    err.join();
    
    0 讨论(0)
提交回复
热议问题