User Tools

Site Tools

blog:2023-03_15_c_process_tasks_kill_by_process_id



2023-03-15 C#: Process Tasks Kill by Process ID

  • Here is the code that is used for killing the task and child tasks by giving the process task id.

Solution

  • static int VAR_ProcessIdOfIpeCmd = 0;
    
    private void Task_StopFirmwareFlashing()
    {
      // 刪除所紀錄的Process與其Child Process
      RecursiveTask_KillProcessAndChildren(VAR_ProcessIdOfIpeCmd);
    }
    
    private void Task_StopFirmwareFlashing()
    {
      // 刪除所紀錄的Process與其Child Process
      RecursiveTask_KillProcessAndChildren(VAR_ProcessIdOfIpeCmd);
    }
    
    private static void RecursiveTask_KillProcessAndChildren(int pid)
    {
      // 這是一個遞迴的程序,會針對所有以傳入之pid為parent Process
      // 的Process,再重複遞迴找尋,直到所有最終沒有任何Procee以其為parent
      // 的Process, 將之進行關閉 Process
      // -------------------------------------
      // 無法刪除(關閉) 'system idle process'
      if (pid == 0)
      {
        return;
      }
      // 找尋所有之Child Process
      ManagementObjectSearcher searcher = new ManagementObjectSearcher
        ("Select * From Win32_Process Where ParentProcessID=" + pid);
      ManagementObjectCollection moc = searcher.Get();
      // 對每一個Child Process 再遞迴方式找尋一次
      foreach (ManagementObject mo in moc)
      {
        RecursiveTask_KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
      }
      // 沒有Child Process時,嘗試刪除該Process
      try
      {
        Process proc = Process.GetProcessById(pid);
        proc.Kill();
      }
      catch (ArgumentException)
      {
        // Process already exited.
      }
    }

References

TAGS

  • 106 person(s) visited this page until now.

Permalink blog/2023-03_15_c_process_tasks_kill_by_process_id.txt · Last modified: 2023/03/16 10:59 by jethro

oeffentlich