简体   繁体   中英

How to differentiate multiple processes with the same name and to kill all those processes which are running with my USERNAME in C#?

I have multiple process named COM SURROGATE (dllhost.exe) are running in Task Manager at my System. In which I need to kill all those processes which are running with my USERNAME(One is running with SYSTEM/"" so no need to kill that).

I need to do like below but only for the dllhost process running with myusername :

Process[] runningProcess = Process.GetProcessesByName("dllhost");
                if(runningProcess.Length > 0 )
                {
                    foreach (var surrogateProcess in runningProcess)
                    {
                        surrogateProcess.Kill();
                    }
                }
  

I found the solution for this. Below are the key points : We can't close process running by SYSTEM/""/otheruser etc without admin access so process.kill() used to throw Access Denied error.

By using below we are trying to terminate all the process with the name of dllhost.exe (we can write any of the process name) and used Style.Hidden so user will not see the cmd prompt and not even the message. Message could be like : ERROR: The process "dllhost.exe" with PID 6332 could not be terminated. Reason: Access is denied. [This is running with either system or other user] SUCCESS: The process "dllhost.exe" with PID 15320 has been terminated. [This was running with my username which can be closed without any issue]

System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "cmd.exe";
                startInfo.Arguments = "/C taskkill /IM dllhost.exe /F";
                process.StartInfo = startInfo;
                process.Start();

The code will close all the processes running with my username only. Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM