Search code examples
c#javawindowsprocesstasklist

Most efficient way to scan the windows process list?


So I'm currently working on a project that needs to time when certain processes are running. I'm trying to figure out the most efficient way to scan the process list, then check the process list executable names against the list of supported programs.

Essentially the problem is two parts:

1) Most efficient way to get the process executable names from the process list

2) Most efficient way to compare this list to another list

For (1), one of the other developers was playing around with using the tasklist command and parsing out the executable names. I also found out that C# has a System.Diagnostic process list that will do this automatically. We're still trying to decide between Java and C# so I probably would lean towards a language neutral solution, but this could be a deciding factor for C#.

For (2), supported process list might be small on average (1-10 process names). We could just run each process through the list, but we were thinking this might be too much for older PCs, so we were tossing around the idea of using an alphabetically balanced AVL tree containing the initial process list when the application starts, and checking everything against that first, and then checking against our supported process names list if its not in the tree.

Any suggestions are greatly appreciated.

Edit: Apparently you can filter tasklist by process executable name, so we could just do that for every process on the supported process list.

Edit 2: Is there a tasklist equivalent that works for Windows XP Home ?


Solution

  • If you go with tasklist, it might actually be faster to just run the command once and get back all of the results, rather than running it for each of your executable names. There is some overhead for exec'ing a process, and getting the output. (When you get back the results, you'll have to loop through them in code, but this might be faster. Normally there won't be more than 100 processes running at once, so it won't be too bad.) You should write a test and check to see if that's true.

    In C#, Process.GetProcesses() is the best way to go.

    In Java, there isn't really an equivalent class/method. Getting a process list is pretty OS-specific, so the Java designers must have decided not to integrate/abstract this capability into the base Java classes. You'll probably have to Runtime.getRuntime().exec("tasklist.exe") to get the results on Windows, or exec("ps") on Unix/Linux.