Java - 如何检查 Linux 上是否正在运行另一个(非 Java)进程 [英] Java - how to check whether another (non-Java) process is running on Linux

查看:28
本文介绍了Java - 如何检查 Linux 上是否正在运行另一个(非 Java)进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些奇怪的问题.

I'm having some weird problems with this.

我们正在使用 Xvfb 虚拟桌面管理器,并希望在我继续之前确保它正在运行.使用纯 shell,我可以轻松做到这一点:

We are using Xvfb virtual desktop manager and want to make sure it's running before I continue. Using pure shell, I could do this easily:

    ps -ef | grep Xvfb | grep -v grep

这正是我所需要的,一行包含有关 Xvfb 过程的信息.接下来,我想将其合并到我的 Java 程序中并解析结果并存储正在运行的 Xvfb 进程的 PID.所以我正在尝试这个:

And that gives me exactly what I need, a single line containing information about the Xvfb proc. Next, I want to incorporate this into my Java program and parse the results and store the PID of the running Xvfb process. So I am trying this:

    String line;
    try {
      Process p = Runtime.getRuntime().exec("ps -ef | grep Xvfb | grep -v grep");
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null)
      {
        System.out.println(line);
      }
    } catch (Exception err) {
      System.out.println(err);
    }

奇怪的是,如果我使用ps -ef",当我运行我的应用程序时,我会得到一个巨大的进程列表转储到我的控制台.但如果我使用 |grep 缩小返回的进程列表,我得到零结果.input.readLine() 每次都为空.

The bizarre thing is that if I use "ps -ef", I get a huge list of processes dumped to my console when I run my app. But if I use | grep to narrow the list of processes returned, I get zero results. input.readLine() gets null every time.

我也试过:

    ps -ef | grep Xvfb | grep -v grep | awk {'print $2'}

只是获取进程ID.还有,运气不好.

To just grab the process id. Also, no luck.

有没有其他人经历过这种情况或知道我做错了什么?

Has anyone else experienced this or know what I'm doing wrong?

推荐答案

您正在尝试使用|"这是 shell 特有的管道函数,因此您不能在 java 进程中执行此操作.您可以尝试使用 pidof Xvfb 获取进程 ID.

You're trying to use the "|" which is a pipe function that is particular to the shell, therefore you cannot do it in the java process. You could just try getting the process ID by using pidof Xvfb.

这篇关于Java - 如何检查 Linux 上是否正在运行另一个(非 Java)进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆