How to close std-streams from java.lang.Process appropriate?

后端 未结 3 858
星月不相逢
星月不相逢 2021-01-01 06:00

This question is about java.lang.Process and its handling of stdin, stdout and stderr.

We have a class in our project that is an extension to org.

3条回答
  •  萌比男神i
    2021-01-01 06:41

    As the question you linked to states, it is better to read and discard the output and error streams. If you are using apache commons io, something like,

    new Thread(new Runnable() {public void run() {IOUtils.copy(process.getInputStream(), new NullOutputStream());}}).start();
    new Thread(new Runnable() {public void run() {IOUtils.copy(process.getErrorStream(), new NullOutputStream());}}).start();
    

    You want to read and discard stdout and stderr in a separate thread to avoid problems such as the process blocking when it writes enough info to stderr or stdout to fill the buffer.

    If you are worried about having two many threads, see this question

    I don't think you need to worry about catching IOExceptions when copying stdout, stdin to NullOutputStream, since if there is an IOException reading from the process stdout/stdin, it is probably due to the process being dead itself, and writing to NullOutputStream will never throw an exception.

    You don't need to check the return status of waitFor().

    Do you want to wait for the process to complete? If so, you can do,

    while(true) {
         try
         {
             process.waitFor();
             break;
         } catch(InterruptedException e) {
             //ignore, spurious interrupted exceptions can occur
         }
    
    }
    

    Looking at the link you provided you do need to close the streams when the process is complete, but destroy will do that for you.

    So in the end, the method becomes,

    public void close(Process process) {
    
        if(process == null) return;
    
        new Thread(new Runnable() {public void run() {IOUtils.copy(process.getInputStream(), new NullOutputStream());}}).start();
        new Thread(new Runnable() {public void run() {IOUtils.copy(process.getErrorStream(), new NullOutputStream());}}).start();
        while(true) {
            try
            {
                process.waitFor();
                //this will close stdin, stdout and stderr for the process
                process.destroy();
                break;
            } catch(InterruptedException e) {
                //ignore, spurious interrupted exceptions can occur
            }
    
       }
    }
    

提交回复
热议问题