3

I have two different .jar programs running on the same machine. I want to be able to detect when one of them has been closed, or is no longer running.

This issue that I am having is, when running this code:

  var allProc = Process.GetProcesses();
  foreach (var p in allProc)

  comboBox1.Items.Add(p.ProcessName);
  comboBox1.Sorted = true;

It only shows a single instance of Java running, and not only that it doesn't show either of the process names.

The program I want to monitor uses a lot of RAM, so I thought about monitoring RAM usage and doing what I need when it drops below a certain level, but to me that sounds like a hacky way of doing it and other factors could effect it.

Any ideas?

3 Answers 3

2

You can use System.Diagnostics.Process to get the Process Id for the parent process you're looking for.

From there you can then use WMI through the (System.Management) namespace to search for the child processes:

Process[] javaProcesses = Process.GetProcessesByName("somejavaapp.exe");
foreach (Process proc in javaProcesses)
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(
    "SELECT * " +
    "FROM Win32_Process " +
    "WHERE ParentProcessId=" + proc.Id);

    ManagementObjectCollection collection = searcher.Get();

    // Choose what to do with the child processes.
    foreach (var childProcess in collection)
    {
        var childProcessId = (UInt32)childProcess["ProcessId"];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

I had the same Issue a while ago, the best Solution for me was to run the java Programm as child.

Example

  server = new Process();
  server.StartInfo.FileName = "java";
  server.StartInfo.Arguments = "-Xmx4000M -jar forge.jar nogui";
  server.Start();

Then Simply

  status = server.HasExited;

Comments

1

There is a command line tool that comes with the JDK called jps. jps -v shows all the arguments you have passed to java. It provides the following output:

lvmid [ [ classname | JARfilename | "Unknown"] [ arg* ] [ jvmarg* ] ]

You can call jps from c# and then read the output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.