Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a process ID exists

Tags:

c#

.net

process

pid

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?

like image 607
Ken Avatar asked Oct 09 '09 18:10

Ken


People also ask

How do you know if a process is alive?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

Which command is used to find the process ID?

tlist (List Process IDs) command will display a list of all PIDs on that system.

How do I find the process of a PID in Linux?

In this quick article, we've explored how to get the name and the command line of a given PID in the Linux command line. The ps -p <PID> command is pretty straightforward to get the process information of a PID. Alternatively, we can also access the special /proc/PID directory to retrieve process information.


1 Answers

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);
}
like image 133
JaredPar Avatar answered Sep 27 '22 16:09

JaredPar