Michael Pfiffer
Michael Pfiffer

Reputation: 115

Check if Java App is running from C# .NET

I launch a game server application from a .bat file currently using this...

java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui

I would like to be able to check if it is running or not from a C# .NET application. Is there any simple way to do this?

Upvotes: 2

Views: 2526

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134841

Using the Process class, you can find the java processes but you won't be able to tell what they are executing. You'd need to be able to inspect their command line at least to determine this. If all your Minecraft servers are started with the same command line arguments, you could use WMI to find. You could get the associated associated Process objects if you want to do what you need.

// find all java processes running Minecraft servers
var query =
    "SELECT ProcessId "
    + "FROM Win32_Process "
    + "WHERE Name = 'java.exe' "
    + "AND CommandLine LIKE '%minecraft_server%'";

// get associated processes
List<Process> servers = null;
using (var results = new ManagementObjectSearcher(query).Get())
    servers = results.Cast<ManagementObject>()
                     .Select(mo => Process.GetProcessById((int)(uint)mo["ProcessId"]))
                     .ToList();

You'll need to add a reference to the System.Management.dll library and use the System.Management namespace.

The existence of such processes is enough to know it is running. You could also determine if and when it ends by inspecting each process' properties such as HasExited or wait for it using WaitForExit().

Upvotes: 3

Zach L
Zach L

Reputation: 16262

Instead of using a .bat file to launch java, you might consider looking into the System.Diagnostics.Process from .Net. It has all sorts of goodies for dealing with processes.

If you want to be checking on the game server constantly over a stretch of time, you probably will have to use it with some sort of Thread or BackgroundWorker, but the Process class ought to lead you in the right direction.

Hope this helps.

Upvotes: 0

Related Questions