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?
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.
tlist (List Process IDs) command will display a list of all PIDs on that system.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With