日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C#結(jié)束進(jìn)程及子進(jìn)程_C#教程

作者:天方 ? 更新時(shí)間: 2022-08-10 編程語言

這是個(gè)我在C#調(diào)用批處理文件時(shí)遇到的問題。首先我通過Process.Start方法調(diào)用一個(gè)批處理文件,那個(gè)批處理文件里面則調(diào)用了一大堆程序。當(dāng)退出C#程序時(shí),我在程序中結(jié)束殺掉了那個(gè)批處理文件的Process,但是,那個(gè)批處理所調(diào)用的子進(jìn)程卻無法像直接調(diào)用批處理文件那樣隨著批處理文件的進(jìn)程一起被殺掉,而是自動向上提升成為了獨(dú)立的進(jìn)程。

在網(wǎng)上查了一下,可以通過NtQueryInformationProcess函數(shù)查詢子進(jìn)程的信息,并同時(shí)也查到了一段殺掉進(jìn)程及所有子進(jìn)程的C#代碼,有需要的朋友可以參考一下。

    static class ProcessExtend
    {
        // [StructLayout(LayoutKind.Sequential)]
        private struct ProcessBasicInformation
        {
            public int ExitStatus;
            public int PebBaseAddress;
            public int AffinityMask;
            public int BasePriority;
            public uint UniqueProcessId;
            public uint InheritedFromUniqueProcessId;
        }

        [DllImport("ntdll.dll")]
        static extern int NtQueryInformationProcess(
           IntPtr hProcess,
           int processInformationClass /* 0 */,
           ref ProcessBasicInformation processBasicInformation,
           uint processInformationLength,
           out uint returnLength
        );

        public static void KillProcessTree(this Process parent)
        {
            var processes = Process.GetProcesses();
            foreach (var p in processes)
            {
                var pbi = new ProcessBasicInformation();
                try
                {
                    uint bytesWritten;
                    if (NtQueryInformationProcess(p.Handle, 0, ref pbi, (uint)Marshal.SizeOf(pbi), out bytesWritten) == 0) // == 0 is OK
                        if (pbi.InheritedFromUniqueProcessId == parent.Id)
                            using (var newParent = Process.GetProcessById((int)pbi.UniqueProcessId))
                                newParent.KillProcessTree();
                }
                catch { }
            }
            parent.Kill();
        }
    }

PS:今天發(fā)現(xiàn)NtQueryInformationProcess函數(shù)在x64位程序上運(yùn)行無效,?具體原因不明,Google了一下也沒有找到答案,反而找到了另一種解決方案,通過WMI來實(shí)現(xiàn)的。在x86和x64下都可以使用。

static void KillProcessAndChildren(int pid)
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
    ManagementObjectCollection moc = searcher.Get();
    foreach (ManagementObject mo in moc)
    {
        KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
    }
    try
    {
        Process proc = Process.GetProcessById(pid);
        Console.WriteLine(pid);
        proc.Kill();
    }
    catch (ArgumentException)
    { 
        /* process already exited */
    }
}

原文鏈接:https://www.cnblogs.com/TianFang/archive/2010/05/19/1739614.html

欄目分類
最近更新