CS Student
CS Student

Reputation: 1643

Using `Runtime.getRuntime().exec()` to get the output from `top`

I'd like run the top -n 1 command using Runtime.getRuntime().exec(String) method and get the output of top -n 1 into my Java program.

I've tried the standard way of getting a processes output with a BufferedReader and using the returned Processes InputStream but that returned no data.

I also tried the following...

        String path = "/home/user/Desktop/";
        String cmd = "#!/bin/sh\ntop -n 1 > " + path + "output";
        File shellCmd = new File(path + "topscript.sh");
        PrintWriter writer = new PrintWriter(shellCmd);
        writer.write(cmd);
        writer.flush();
        Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath()); 
        Runtime.getRuntime().exec(shellCmd.getAbsolutePath());

Which creates the shell script and the output but the output is empty. However, if I then load up my local shell and run the script that the code above made, I get the correct output in the output file.

What's going wrong?

Upvotes: 2

Views: 2036

Answers (1)

chengpohi
chengpohi

Reputation: 14227

    String cmd = "#!/bin/sh\ntop -n1 -b > " + path + "output";
    File shellCmd = new File(path + "topscript.sh");
    PrintWriter writer = new PrintWriter(shellCmd);
    writer.write(cmd);
    writer.flush();
    Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(shellCmd.getAbsolutePath());
    Map<String, String> enviornments = pb.environment();
    enviornments.put("TERM", "xterm-256color");
    Process process = pb.start();

    BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    String str = inputStreamReader.readLine();
    System.out.println(str);
    System.out.println(errorStreamReader.readLine());

Use ProcessBuilder with setting TERM variables.

and if want to redirect top to file. need to add -b option to avoid error: initializing curses.

Upvotes: 3

Related Questions