How to kill process regardless whether it's 32 or 64-bit?

前端 未结 2 1781
面向向阳花
面向向阳花 2021-01-23 23:35

In my tool at a certain point I want to kill a process by it\'s name. I\'m testing now on Win7 64-bit, but the error I receive is:

A 32 bit processes cann

相关标签:
2条回答
  • 2021-01-24 00:19

    Use Process.GetProcessesByName(), which will in most cases by identical to looking for the name of (main) module. You will still have to deal with the fact, that this will return multiple processes,so you may or may not want to kill all of them, but, YMMV.

    foreach (Process process in Process.GetProcessesByName("communicator"))
    {
        process.Kill();
    }
    

    Also note that the Kill method runs asynchronously, i.e. it may return before the respective process has actually been killed. You could add a Process.WaitForExit() if you care.

    0 讨论(0)
  • 2021-01-24 00:28

    It is not the Kill() call that fails, it is the foreach on process.Modules. Which is very problematic in a 32-bit process when the target process is 64-bit, this doesn't get emulated perfectly in the Wow64 emulation layer. That's surely a //TODO comment somewhere in the Windows source code with good odds that it just can't easily be implemented.

    You'll have to make do with the Process.Name property. Or change your project's Target platform setting in the Compile tab to AnyCPU so that you'll run as a 64-bit process as well. Using the Modules property like you do doesn't otherwise make the code any safer, you are just as likely to kill the wrong process.

    0 讨论(0)
提交回复
热议问题