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

问题描述



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

  ps -ef | grep Xvfb | grep -v grep 

这就给我提供了我需要的东西,一行包含关于Xvfb PROC。接下来,我想将它结合到我的Java程序中,并解析结果并存储正在运行的Xvfb进程的PID。所以我想这样做:

 字符串行; 
尝试{
Process p = Runtime.getRuntime()。exec(ps -ef | grep Xvfb | grep -v grep);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); ((line = input.readLine())!= null)

{
System.out.println(line);
}
} catch(Exception err){
System.out.println(err);

$ / code>

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



我也试过:

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

只需获取进程ID。

有没有其他人经历过这样的事情,或者知道我做错了什么?

解决方案

您试图使用|这是shell特有的管道功能,因此你不能在java进程中执行它。您可以尝试使用 pidof Xvfb 来获取进程ID。


I'm having some weird problems with this.

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

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);
    }

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.

I have also tried:

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

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

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

解决方案

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 - 如何检查另一个(非Java)进程是否在Linux上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:20