0

I'm using OpenNETCF 2.3 in a .NET Compact Framework 3.5 mobile device application. At program startup I am looking for duplicate running instances of my application. I am confused why the current ProcessID I get from various methods seems to be incorrect about half the time.

Public Shared Sub Main()
    Dim appName As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name & ".exe"
    Dim intCurrentProcessId As Integer = OpenNETCF.Diagnostics.ProcessHelper.GetCurrentProcessID
    'Dim intCurrentProcessId As Integer = Process.GetCurrentProcess.Id()

    For Each p As ToolHelp.ProcessEntry In ToolHelp.ProcessEntry.GetProcesses
        If p.ProcessID <> intCurrentProcessId AndAlso p.ExeFile.Contains(appName) Then
            MessageBox.Show("KILLING p.ExeFile: " & p.ExeFile & " p.processid: " & p.ProcessID & " intCurrentProcessId: " & intCurrentProcessId)
            'p.Kill()
        End If
    Next
End Sub

Why is it that intCurrentProcessId would seemingly randomly not match p.ProcessId and be a negative number?

My rep is too low to post a screenshot that shows p.ProcessID = 3459667490 and intCurrentProcessID = -835299806.

Please understand that alternate methods of testing for single instances don't interest me. Thank you.

Jason
  • 13
  • 5
  • So you want to kill every proc that is **not** the same PID and contains the appName? – Mathemats Feb 03 '15 at 01:01
  • Correct. I would also like to know why the current process ID is returned incorrectly half of the time. – Jason Feb 03 '15 at 01:12
  • If you have multiple instance of your process running then you would *expect* there to be something like " p.ProcessID = 3459667490 and intCurrentProcessID = -835299806" because one is the new instance and one is the old. And having a negative process ID doesn't matter, treat it as an opaque identifier. – tcarvin Feb 03 '15 at 14:23
  • I agree, however, I don't think it's a valid PID. It does not show up in any task manager. Also, currently there is not much possibility of previous instances of the app running in the background as the test code only checks PID's, displays a message, then exits. Of the roughly 50% of the time the PID's don't match, 100% of the time they are signed/negative. – Jason Feb 03 '15 at 18:56

1 Answers1

1

First, a quick look at signed versus unsigned numbers (feel free to use Calculator on your desktop to validate these).

3459667490 in unsigned decimal is 0xCE365622 in 32-bit hex.
-835299806 in signed decimal is 0xCE365622 in 32-bit hex.

See the similarity?

If you cast so the are both either signed or unsigned I'm willing to bet that 100% of the time the ID's will match.

ctacke
  • 66,480
  • 18
  • 94
  • 155