1

Process.Handle is returning different values every time, is this correct? From msdn, "The handle that the operating system assigned to the associated process when the process was started. The system uses this handle to keep track of process attributes." https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.handle?view=netcore-3.1

Isn't supposed to be constant if not unique?

Tried different ways of getting the process but the Handle is different everytime. Ex:

Process.GetProcesses().FirstOrDefault(...)

OR

Process.GetProcessById(123)

OR

Process.GetProcessesByName("xyz")

I'm trying to hold a process id of a process that is launched by my application and this id will be used "later" to get the process from the running processes to stop it, if it is still running in a particular case. I don't want to check with name as the same application can be launched externally.

Trying to add another layer of validation to make sure any other process is not running with same id later(if my expected process is already stopped and the same id is used for restarting same application or any other application)

Is the Process.Handle property expected to be varying or Any other way to do the same?

Roman Kalinchuk
  • 718
  • 3
  • 14
DevMindzz
  • 21
  • 4
  • 1
    Read bottom of following answer : https://stackoverflow.com/questions/14020430/how-to-get-ppid – jdweng Jun 24 '20 at 11:21

2 Answers2

2

It's "a handle for a process" not "the handle for a process". It is a quantity that allows a program to operate on a process, not the sole identifier of a process.

The same is true for any other Windows kernel handle. For example, if you open the same file twice by 'the usual methods', you'll have two different handles for the same thing.

As long as the process has not terminated or there is still one handle open that refers to the process, its process id is the actual unique identification. The id can be reused later however.

I can't answer why the documentation says what it does.

user13784117
  • 1,124
  • 4
  • 4
0

'm trying to hold a process id of a process that is launched by my application and this id will be used "later" to get the process from the running processes to stop it,

Just hold onto the Process instance, then you can skip the "get the process from the running processes".

You need to do this anyway to prevent the process ID from being reused. The process ID is constant for the lifetime of the process-tracking kernel data object, which really means "as long as either the process is alive or someone keeps an open handle to it". By keeping a Process object instance, you keep a handle open, and keep the process ID valid.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720