首页 > 解决方案 > Process.Modules 随机给出不同的进程名称

问题描述

我试图启动 %PATH% 环境变量中存在的进程(没有完整路径),并通过 Process Objects Modules 属性获取其路径。

大多数情况下它都有效,但有时 Modules 属性包含路径C:\Windows\SYSTEM32\ntdll.dll

这是一个简单的 vb.net 代码来重现该问题

  Sub checkNtdllError()
        ' Run in a While Loop as this issues is reproduced rarely

        While True
            Dim psi = New ProcessStartInfo
            With psi
                .FileName = "cmd.exe"
                .Arguments = "/c echo 'Hello'"
                .RedirectStandardError = True
                .RedirectStandardOutput = True
                .RedirectStandardInput = True
                .CreateNoWindow = True
                .UseShellExecute = False
            End With


            Try
                'Start a new Process of cmd.exe (from the %PATH% environment variable)
                Dim proc = Process.Start(psi)

                Dim moduleName = "Unknown"
                If proc.Modules.Count > 0 Then
                    moduleName = proc.Modules(0).FileName
                Else
                    If Debugger.IsAttached Then Debugger.Break()
                    ' Question: Why proc.Modules.Count was 0?
                    Continue While
                End If

                Console.WriteLine(moduleName) ' This should print the full path of cmd.exe in the console

                If Not moduleName.Contains("cmd") Then
                    ' Question: Why was the ModuleName ntdll.dll?

                    Dim stdOut = proc.StandardOutput.ReadToEnd()
                    Dim stdErr = proc.StandardError.ReadToEnd
                    proc.WaitForExit()
                    proc.Dispose()

                    Dim procOut = stdOut & stdErr
                    Console.WriteLine("  " & procOut)
                    ' Observer here that even when the Module Name was not cmd.exe, still the process output was correct
                    If Debugger.IsAttached Then Debugger.Break()
                    Console.WriteLine("--------------------------------------------------")

                End If


            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try

        End While

        Console.Read()
    End Sub

期望 如果在路径中找到 cmd.exe,它应该总是在 ModuleName 中打印 cmd.exe 的路径

问题:

  1. 为什么有时 proc.Modules 数组是空的?
  2. 为什么有时 proc.Modules 数组包含 ntdll.dll 的路径?

标签: .netprocess

解决方案


推荐阅读