【问题标题】:Using `Runtime.getRuntime().exec()` to get the output from `top`使用 `Runtime.getRuntime().exec()` 从 `top` 获取输出
【发布时间】:2015-12-09 13:55:21
【问题描述】:

我想使用Runtime.getRuntime().exec(String) 方法运行top -n 1 命令并将top -n 1 的输出输入到我的Java 程序中。

我尝试了使用BufferedReader 获取进程输出并使用返回的进程InputStream 的标准方法,但没有返回任何数据。

我也尝试了以下...

        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());

创建shell script 和输出,但输出为空。但是,如果我随后加载我的local shell 并运行上面代码生成的script,我会在输出文件中得到正确的输出。

What's going wrong?

【问题讨论】:

  • 你得到错误输出流吗?比如p.getErrorStream(),内容是什么?
  • @chengpohi 啊我不知道那个方法。它给了我TERM environment variable not set.
  • @chengpohi 所以它无法执行脚本但它可以创建脚本然后chmod 它。怎么chmod它却不能运行?
  • 因为当你使用 Java 运行一个 bash 脚本时,它会生成一个新的 shell 来运行它而不需要 env 变量。
  • 考虑使用top -n 1 -b 使输出对文本文件更友好。

标签: java shell output exec


【解决方案1】:
    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());

使用 ProcessBuilder 设置 TERM 变量。

如果想将top 重定向到文件。需要添加-b选项来避免error: initializing curses

【讨论】:

  • 您可能希望使用top -n 1 -b 使输出更适合重定向到文件。
  • @Cinnam 谢谢,没有-b 将导致error: initializing curses
猜你喜欢
  • 2011-06-12
  • 2014-05-24
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2012-10-14
  • 2011-01-09
  • 2015-08-28
  • 2012-09-08
相关资源
最近更新 更多