简体   繁体   中英

Runtime.exec - fine for 'echo' 'but not for cat…

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;
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM