views:

670

answers:

3

I'm using C# .NET 2.0. I need to determine if a PID exists. I came up with the following code:

private bool ProcessExists(int iProcessID)
{
    foreach (Process p in Process.GetProcesses())
    {
        if (p.Id == iProcessID)
        {
            return true;
        }
    }
    return false;
}

Is there a better way to do this other than iterating all the processes?

Thanks!

+1  A: 

Quick Note: You can't ever determine if a process, other than your own, is running. You can only tell that it was running at some point in the recent past. A process can simply cease to exist at any given moment including the exact moment you check to see if it has a matching ID.

That being said, this type of determination may or may not be good enough for your program. It really depends on what you are trying to do.

Here is an abbreviated version of the code you wrote.

private bool ProcessExists(int id) {
  return Process.GetProcesses().Any(x => x.Id == id);
}
JaredPar
A: 

System.Diagnostics.Process.GetProcessById(iProcessID) would throw ArgumentException if the process doesn't exist. Although that is not the best way to check if the process exists, but hopefully this is what you're looking for.

Yuriy Faktorovich
Thanks for the suggestion, but I generally err against catching exceptions when attempting to resolve some value, as standard practice.
Ken
I agree, but was hoping this is what your program was looking for, couldn't think of a reason to check if a specific process id was alive.
Yuriy Faktorovich
+3  A: 

The risky thing here is: Where did you get that Process ID from? If it's just a number you saved sometime earlier, the original process could have died and a new process could be running with the same ID.

What are you trying to accomplish? There may be a better way of achieving your actual goal.

Eric J.
The PID is reliable. It is the PID of a second application that launches my application. The second application is guaranteed to always be running while my application is running. (My application is essentially a DialogBox that has the second application as its parent.) Other than that, the Frankenstein details aren't worth getting into for the sake of this question. Thanks.
Ken
But your question is about determining whether it is running. If it's guaranteed to be running, why do you have to check?
Eric J.
Good point. It's a sanity check in case the exceptional case does in fact happen for some reason that is beyond me. I'll edit the question text to better represent what the sample code is actually doing. Thanks.
Ken