user8843856
user8843856

Reputation: 13

Is there a way to find a process on top of the process id and name in c#

I have multiple processes started and I want to keep track of each of them so that I can start the process again if it ended without my knowledge.

Currently, I store the process id in my database and I use the process id and name to check if the process is still running.

Process process=Process.GetProcessById(id);
if(process.ProcessName==processName){
 //kill the process
}

However, I was reading online that when a process dies, its id will be free for other processes to use. There could be a chance that there will be a new process with my old process id and name which might lead me to assume my old process is still running.

Is there any additional fields I can add to make my process unique? such as the process site? I am unable to get more information on what the process site is used for.

Upvotes: 1

Views: 608

Answers (2)

Chris Catignani
Chris Catignani

Reputation: 5306

Run this piece of code and look at the available properites of

runningProcesses

...

    private static void KillProcess(string processName)
    {
        Process[] runningProcesses = Process.GetProcesses();
        foreach (Process process in runningProcesses)
        {
            if (process.ProcessName == processName)
            {
                process.Kill();
            }
        }
    }

You could create your process with a unique BasePriority or something similar.

Documentation

Upvotes: 0

rob.earwaker
rob.earwaker

Reputation: 1286

You could store the Process.StartTime property in addition to its ID. That should protect you in the case that the PID has been re-used since the new process would have a different start time to the one stored.

var process = Process.GetProcessById(id);

if (process.ProcessName == processName && process.StartTime == startTime)
{
    //kill the process
}

I suspect the following does not apply since you're persisting process information, but if your application is continually monitoring these processes then you might consider using the Process.Exited event to receive notifications when a process exits rather than checking every so often, e.g.

process.EnableRaisingEvents = true;
process.Exited += (sender, args) => { /* Do something */ };

Upvotes: 2

Related Questions