简体   繁体   English

执行命令

[英]Executing a command

I'm trying to execute a command: 我正在尝试执行命令:

public static void main(String[] args) {        
    int buffer;
    StringBuilder res = new StringBuilder();
    Process proc;
    try {
        proc = Runtime.getRuntime().exec("cat /proc/stat | grep 'btime' | awk '{print $2}'");
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String line;
        while ((line=reader.readLine())!=null) {
            System.out.println(line);
        }
        proc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But the result is not what I expected: 但是结果却不是我所期望的:

cat: '|': No such file or directory
cat: grep: No such file or directory
cat: "'btime'": No such file or directory
cat: '|': No such file or directory
cat: awk: No such file or directory
cat: ''\''{print': No such file or directory
cat: '$2}'\''': No such file or directory

What am I doing wrong? 我究竟做错了什么? Ubuntu 18.04. Ubuntu 18.04。

Runtime.exec cannot run arbitrary shell/terminal commands like this. Runtime.exec无法运行这样的任意shell / terminal命令。

You have to run the bash program and then send your command as parameter to bash. 您必须运行bash程序,然后将命令作为参数发送到bash。 Bash will do the job for you. Bash将为您完成这项工作。

https://stackoverflow.com/a/15356451/1364747 https://stackoverflow.com/a/15356451/1364747

This is OS specific. 这是特定于操作系统的。 On a different OS it might be a different command/terminal. 在不同的操作系统上,它可能是不同的命令/终端。 Also you might need to know the path to that program. 另外,您可能需要知道该程序的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM