欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

runtime无法执行grep_如何使管道使用Runtime.exec()?

发布时间:2025/3/12 编程问答 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 runtime无法执行grep_如何使管道使用Runtime.exec()? 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

慕运维8079593

我在Linux中遇到了一个类似的问题,只不过是“ps-ef_grep找进程”。至少使用“ls”可以替换与语言无关(尽管速度较慢)的Java。例如:File f = new File("C:\\");String[] files = f.listFiles(new File("/home/tihamer"));for (String file : files) {

    if (file.matches(.*some.*)) { System.out.println(file); }}有了“ps”,这就有点难了,因为Java似乎没有相应的API。我听说西格也许能帮到我们:https:/Support.hyperic.com/Display/SIGAR/Home然而,最简单的解决方案(正如Kaj所指出的)是以字符串数组的形式执行管道命令。以下是完整的代码:try {

    String line;

    String[] cmd = { "/bin/sh", "-c", "ps -ef | grep export" };

    Process p = Runtime.getRuntime().exec(cmd);

    BufferedReader in =

            new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((line = in.readLine()) != null) {

        System.out.println(line); 

    }

    in.close();} catch (Exception ex) {

    ex.printStackTrace();}为什么字符串数组与管道一起工作,而单个字符串不能.这是宇宙之谜之一(尤其是如果你还没有读过源代码)。我怀疑这是因为当给EXEC一个字符串时,它首先解析它(以我们不喜欢的方式)。相反,当向exec提供字符串数组时,它只是将其传递给操作系统,而不对其进行解析。实际上,如果我们从繁忙的一天抽出时间来查看源代码(见http:/grepcode.com/file/pository.grepcode.com/java/root/JDK/OpenJDK/6-b14/java/lang/Runtime.java#Runtime.exec%28java.lang.String%2 Cjava.lang.String[]%2 Cjava.io.File%29),我们发现这正是正在发生的事情:public Process  [More ...] exec(String command, String[] envp, File dir) 

          throws IOException {

    if (command.length() == 0)

        throw new IllegalArgumentException("Empty command");

    StringTokenizer st = new StringTokenizer(command);

    String[] cmdarray = new String[st.countTokens()];

    for (int i = 0; st.hasMoreTokens(); i++)

        cmdarray[i] = st.nextToken();

    return exec(cmdarray, envp, dir);}

总结

以上是生活随笔为你收集整理的runtime无法执行grep_如何使管道使用Runtime.exec()?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。