Closing process causes high cpu usage in input.readLine()

Viewed 152

I have code that runs cmd.exe process with ProcessBuilder and when I destroy this process with process.destroy(); the CPU usage incrases (0% > 30%). Every time I start and destroy cmd.exe new Threads appear that causes cpu usage up to 100%. Can I somehow stop this loop when the InputStream ends? It is also the same in my another app when Server stops with eg Ctrl-C and client have high cpu usage.

input.readLine(); wants to read from not exisitng InputStream and causes high cpu usage. It is stuck at this line.

I use Java 8

Code:

InputStream inputraw = process.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(inputraw));
while(true)    
{
    String cmd = input.readLine(); //HERE!
    //write cmd to console functions.....
}
if (isWindows) {
    command = (String.format("cmd.exe"));
} else {
    command = (String.format("sh"));
}
ProcessBuilder pb = new ProcessBuilder()
    .command(command)
    .redirectErrorStream(true);
process = pb.start();
1 Answers

I've found some solution to this problem:

(If you want to post better answer you can still do it)

    public static String readLine(InputStream s) throws Exception {
        String cmd = "";
        try {
            int ch = s.read();
            cmd += (char) ch;
            StringBuilder cmdBuilder = new StringBuilder(cmd);
            while (ch != 10 && ch >= 0) {
                ch = s.read();
                if (ch == 10 || ch < 0) break;
                cmdBuilder.append((char) ch);
            }
            cmd = cmdBuilder.toString();
        } catch (Exception ex) {
            throw new Exception("Input was empty!");
        }
        return cmd;
    }
Related