为什么Runtime.exec(String)适用于一些而不是所有的命令?

当我尝试运行Runtime.exec(String) ,某些命令工作,而其他命令执行,但失败或做不同于我的terminal。 这里是一个自包含的testing用例,演示了这个效果:

 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 worldreplace命令,但是对于其他命令(尤其是那些涉及具有类似于这里的空格的文件名的命令),这个例子工作的很好,即使命令显然正在执行,我也会得到错误:

 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 

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

为什么一些命令失败?

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

什么时候命令失败?

一个命令将会失败,只要它依赖于一个shell的特性。 shell做了很多我们通常不会想到的常见,有用的东西:

  1. shell在引号和空格处正确分割

    这确保"My File.txt"的文件名仍然是单个参数。

    Runtime.exec(String)天真地分裂空间,并将通过这两个单独的文件名。 这显然失败了。

  2. shell扩大globs /通配符

    当你运行ls *.doc ,shell将它重写成ls letter.doc notes.doc

    Runtime.exec(String)不,它只是将它们作为parameter passing。

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

  3. shellpipe理pipe道和redirect。

    当你运行ls mydir > output.txt ,shell打开命令输出的“output.txt”并将它从命令行中删除,并给出ls mydir

    Runtime.exec(String)不。 它只是将它们作为parameter passing。

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

  4. shell扩展了variables和命令

    当你运行ls "$HOME"或者ls "$(pwd)" ,shell会把它重写成ls /home/myuser

    Runtime.exec(String)不,它只是将它们作为parameter passing。

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

安全可靠:承担shell的责任。

这不是一个可以机械地应用的修复,但是需要了解Unix的执行模式,shell是做什么的,以及如何做到这一点。 但是,您可以通过从图片中提取壳来获得稳定,安全和可靠的解决scheme。 这由ProcessBuilder促进。

前面示例中需要某人处理1.引号,2.variables和3.redirect的命令可以写为:

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