使用 Runtime.getRuntime().exec 时遇到问题 [英] Trouble using Runtime.getRuntime().exec
问题描述
我在 mac 中使用以下 cmds 但它不起作用,对此有何想法?
I am using the below cmds in mac and It doesn't work, any thoughts on this?
String[] cmdline = { "echo", "symc", "|", "sudo", "-S", "rm", "-f", "/Applications/Test application.app" };
Runtime.getRuntime().exec(cmdline);
我也尝试过,但没有成功:
I also tried but in vain:
Process p = Runtime.getRuntime().exec("echo symc | sudo -S rm -rf /Applications/Test application.app");
有什么建议吗?
推荐答案
您传递给 exec
的不是在 shell 中运行的任意命令行,而是要启动的进程的名称与其论据.因此,如果你想要管道,甚至只是 echo
命令,它不是一个常规的可执行文件,你必须显式地启动一个新的 shell,沿着命令行传递执行.类似的东西
What you pass to exec
is not an arbitrary command line that works in a shell, but the name of a process to start along with its arguments. Therefore, if you want piping, and even just the echo
command, which is not a regular executable, you must start a new shell explicitly, passing along the command line to execute. Something like
sh -c echo ...
所以这应该有效:
String[] cmdline = { "sh", "-c", "echo symc | sudo -S rm -rf /Applications/Test application.app" };
Runtime.getRuntime().exec(cmdline);
注意,如果你想使用管道,你应该只给 -c
一个参数.
Note that you should give -c
only a single argument if you want to use pipes.
这篇关于使用 Runtime.getRuntime().exec 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!