[英]ProcessBuilder("command","-v","date").start() fails with IOException: No such file or directory
I am trying to find out whether a command exists (eg. date
) using the command
shell builtin, on Ubuntu. However the following (scroll further below for java snippet)我正在尝试在 Ubuntu 上使用内置
command
shell 来确定命令是否存在(例如date
)。但是以下内容(在下方进一步滚动以获取 java 片段)
//main.kt
fun main(){
val proc=ProcessBuilder("command","-v","date").start() //line 37
}
fails to run with stack trace无法使用堆栈跟踪运行
Exception in thread "main" java.io.IOException: Cannot run program "command": error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1143)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1073)
at MainKt.main(main.kt:37)
at MainKt.main(main.kt)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:314)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:244)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1110)
... 3 more
command
is definitely available on my bash - command
在我的 bash 上绝对可用 -
user@pc:~$ type command
command is a shell builtin
Why does the error occur?为什么会出现错误?
Note that most other similar queries (there are plenty on SO) got solved via syntactic corrections or bad file paths, and don't apply here.请注意,大多数其他类似的查询(SO 上有很多)通过语法更正或错误的文件路径得到解决,不适用于此处。
Env:环境:
JDK 17 on Ubuntu 20.04.5 LTS Ubuntu 20.04.5 LTS 上的 JDK 17
Java code : Java 代码:
import java.io.IOException;
//rough.java
public class rough {
public static void main(String[] args) throws IOException {
new ProcessBuilder("command","-v","date").start();
}
}
Your first sentence already has the solution:你的第一句话已经有了解决方案:
[…] using the
command
shell builtin […][...] 使用内置
command
shell [...]
ProcessBuilder
execs processes directly and does not invoke a shell. And since a shell-builtin is a functionality provided by the shell and not a binary, it cannot be invoked (directly) with ProcessBuilder
. ProcessBuilder
execs 直接处理并且不调用 shell。并且由于 shell-builtin 是由 shell 提供的功能而不是二进制文件,因此不能(直接)使用ProcessBuilder
调用它。
If you want to run a shell, you need to do so explicitly:如果你想运行 shell,你需要明确地这样做:
new ProcessBuilder("sh", "-c", "command -v date").start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.