【问题标题】:Why does Runtime.exec(String) work for some but not all commands?为什么 Runtime.exec(String) 对某些但不是所有命令都有效?
【发布时间】:2015-10-24 22:13:12
【问题描述】:

当我尝试运行Runtime.exec(String) 时,某些命令可以工作,而其他命令会执行但失败或执行与我的终端不同的操作。下面是一个独立的测试用例来演示效果:

public class ExecTest {
  static void exec(String cmd) throws Exception {
    Process p = Runtime.getRuntime().exec(cmd);

    int i;
    while( (i=p.getInputStream().read()) != -1) {
      System.out.write(i);
    }
    while( (i=p.getErrorStream().read()) != -1) {
      System.err.write(i);
    }
  }

  public static void main(String[] args) throws Exception {
    System.out.print("Runtime.exec: ");
    String cmd = new java.util.Scanner(System.in).nextLine();
    exec(cmd);
  }
}

如果我将命令替换为echo hello world,该示例效果很好,但对于其他命令——尤其是那些涉及带有空格的文件名的命令——即使该命令显然正在执行,我也会收到错误:

myshell$ javac ExecTest.java && java ExecTest
Runtime.exec: ls -l 'My File.txt'
ls: cannot access 'My: No such file or directory
ls: cannot access File.txt': No such file or directory

同时,复制粘贴到我的 shell:

myshell$ ls -l 'My File.txt'
-rw-r--r-- 1 me me 4 Aug  2 11:44 My File.txt

为什么会有差异?它什么时候工作,什么时候失败?如何使它适用于所有命令?

【问题讨论】:

    标签: java runtime.exec


    【解决方案1】:

    为什么有些命令会失败?

    发生这种情况是因为传递给 Runtime.exec(String) 的命令未在 shell 中执行。 shell 为程序执行了很多常见的支持服务,当 shell 不在身边时,命令将失败。

    命令什么时候失败?

    只要依赖于 shell 功能,命令就会失败。 shell 做了很多我们通常不会想到的常见、有用的事情:

    1. shell 在引号和空格上正确拆分

      这确保"My File.txt" 中的文件名保持为单个参数。

      Runtime.exec(String) 天真地分割空格并将其作为两个单独的文件名传递。这显然失败了。

    2. shell 扩展 glob/通配符

      当您运行ls *.doc 时,shell 会将其重写为ls letter.doc notes.doc

      Runtime.exec(String) 没有,它只是将它们作为参数传递。

      ls 不知道* 是什么,所以命令失败。

    3. shell 管理管道和重定向。

      当您运行ls mydir > output.txt 时,shell 会打开“output.txt”用于命令输出并将其从命令行中删除,并给出ls mydir

      Runtime.exec(String) 没有。它只是将它们作为参数传递。

      ls 不知道> 是什么意思,所以命令失败。

    4. shell 扩展变量和命令

      当您运行ls "$HOME"ls "$(pwd)" 时,shell 会将其重写为ls /home/myuser

      Runtime.exec(String) 没有,它只是将它们作为参数传递。

      ls 不知道$ 是什么意思,所以命令失败。

    你能做些什么呢?

    有两种方法可以执行任意复杂的命令:

    简单而草率:委托给外壳。

    您可以只使用Runtime.exec(String[])(注意数组参数)并将您的命令直接传递给可以完成所有繁重工作的shell:

    // Simple, sloppy fix. May have security and robustness implications
    String myFile = "some filename.txt";
    String myCommand = "cp -R '" + myFile + "' $HOME 2> errorlog";
    Runtime.getRuntime().exec(new String[] { "bash", "-c", myCommand });
    

    安全可靠:承担外壳的职责。

    这不是一个可以机械应用的修复程序,但需要了解 Unix 执行模型、shell 的作用以及如何做到这一点。但是,您可以通过去掉外壳来获得可靠、安全和健壮的解决方案。 ProcessBuilder 促成了这一点。

    上一个示例中需要有人处理 1. 引号、2. 变量和 3. 重定向的命令可以写成:

    String myFile = "some filename.txt";
    ProcessBuilder builder = new ProcessBuilder(
        "cp", "-R", myFile,        // We handle word splitting
           System.getenv("HOME")); // We handle variables
    builder.redirectError(         // We set up redirections
        ProcessBuilder.Redirect.to(new File("errorlog")));
    builder.start();
    

    【讨论】:

    • Runtime.getRuntime().exec(new String[] { System.getenv("SHELL"), "-c", myCommand });
    • 首选明确指定您知道可以理解该命令的 shell。您的程序不应仅仅因为用户选择 fishpwsh 作为他们的登录 shell 而停止工作。
    • 似乎“简单而草率”的方法(我认为这对于我正在做的事情来说已经足够了)一次只处理一个命令。如何处理一系列命令?
    • 与shell中的方法相同:用;&&或换行符分隔
    猜你喜欢
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2012-09-10
    相关资源
    最近更新 更多