0

I want to detect, from inside Java, whether another process is executing.

String  args = "ps -efl";
Process p = Runtime.getRuntime ().exec (args);

try
{
    int     exitVal = p.waitFor ();

    // search output for instance of process name
    BufferedReader br = new BufferedReader (new InputStreamReader (p.getInputStream ()));
    String  line = "";
    while ((line = br.readLine ()) != null)
    {
        System.out.println (line);
    }
}
catch (InterruptedException e)
{
    System.out.println (e.getMessage ());
    System.exit (0);
}

You would expect "ps -efl" to produce several dozen lines of output, at least. Instead, I get only:

PID TTY TIME CMD

21025 pts/1 00:00:00 bash

22133 pts/1 00:00:04 java

22169 pts/1 00:00:00 ps

i.e. the process id. of "ps" itself, and the Java session running it, and the bash shell running Java.

Incidentally, executing "bash -c 'ps -efl'", with or without the single quotes, produces no output.

Any idea how to list processes outside the immediate process and its parents?

  • You need to read the output as it is produced, otherwise if a buffer fills up the process will stop waiting for you program to read it, so it is lucky you are not getting back much. Which version of linux are you running? I would expect this output on cygwin. – Peter Lawrey Aug 18 '15 at 16:55
  • uname -a returns "Linux livr-86 2.6.32-279.el6.i686 #1 SMP Wed Jun 13 18:23:43 EDT 2012 i686 i686 i386 GNU/Linux" – Huw7744 Aug 18 '15 at 17:09
  • On my ubuntu desktop it prints all the output you get running `ps -elf` on the command line. I see lots of processes. Note: I moved the `p.waitFor();` to after reading the input. – Peter Lawrey Aug 18 '15 at 17:15
  • That produced the output I expected. Appending a "grep | " to the command line killed the output, but at least I am merely dealing with recalcitrant options now, rather than killing my own output. Thanks for the help. – Huw7744 Aug 18 '15 at 17:28
  • @Huw7744 See http://stackoverflow.com/questions/31776546/why-does-runtime-execstring-work-for-some-but-not-all-commands/31776547 for why piping fails. – that other guy Aug 18 '15 at 17:29
  • Note exec runs exactly one program, it doesn't start a shell to interprete your command. i.e. perhaps you wanted `bash -c 'ps -elf | grep java'` – Peter Lawrey Aug 18 '15 at 17:30

0 Answers0