0

I'm having a problem calling some simple command line functions with r.exec - for some reason, given a file X the command 'echo full/path/to/X' works fine (both in the display and with 'p.exitValue()==0', but 'cat full/path/to/X' does not (and has 'p.exitValue()==1') - both 'cat' and 'echo' live in /bin/ on my OSX - am I missing something? Code is below (as it happens, any suggestions to improve the code generally are welcome...)

private String takeCommand(Runtime r, String command) throws IOException {
        String returnValue;
        System.out.println("We are given the command" + command);
        Process p = r.exec(command.split(" "));
        InputStream in = p.getInputStream();
        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);
        // Read the ls output
        String line;
        returnValue = "";
        while ((line = bufferedreader.readLine()) != null) {
            System.out.println(line);
            returnValue = returnValue + line;
        }
        try {// Check for  failure
            if (p.waitFor() != 0) {
                System.out.println("XXXXexit value = " + p.exitValue());
            }
        } catch (InterruptedException e) {
            System.err.println(e);
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
        try {// should slow this down a little
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return returnValue;
    }
Joe
  • 4,367
  • 7
  • 33
  • 52

1 Answers1

2

You should be consuming stdout and stderr asynchronously.

Otherwise it's possible for the output of the command to block the input buffers and then everything grinds to a halt (that's possibly what's happening with your cat command since it'll dump much more info than echo).

I would also not expect to have to call waitFor() twice.

Check out this SO answer for more info on output consumption, and this JavaWorld article for more Runtime.exec() pitfalls.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440