Find all child processes of my own .NET process / find out if a given process is a child of my own?

后端 未结 2 1084
离开以前
离开以前 2020-11-27 22:30

I have a .NET class library that spins up a secondary process which is kept running until I dispose of the object.

Due to some occurances of the program lingering in

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 22:59

    as it happens I have a bit of C#/WMI code lying around that kills all processes spawned by a specified process id, recursively. the killing is obviously not what you want, but the finding of child processes seems to be what you're interested in. I hope this is helpful:

        private static void KillAllProcessesSpawnedBy(UInt32 parentProcessId)
        {
            logger.Debug("Finding processes spawned by process with Id [" + parentProcessId + "]");
    
            // NOTE: Process Ids are reused!
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(
                "SELECT * " +
                "FROM Win32_Process " +
                "WHERE ParentProcessId=" + parentProcessId);
            ManagementObjectCollection collection = searcher.Get();
            if (collection.Count > 0)
            {
                logger.Debug("Killing [" + collection.Count + "] processes spawned by process with Id [" + parentProcessId + "]");
                foreach (var item in collection)
                {
                    UInt32 childProcessId = (UInt32)item["ProcessId"];
                    if ((int)childProcessId != Process.GetCurrentProcess().Id)
                    {
                        KillAllProcessesSpawnedBy(childProcessId);
    
                        Process childProcess = Process.GetProcessById((int)childProcessId);
                        logger.Debug("Killing child process [" + childProcess.ProcessName + "] with Id [" + childProcessId + "]");
                        childProcess.Kill();
                    }
                }
            }
        }
    

提交回复
热议问题