当父进程被杀死时杀死子进程


156

我正在使用System.Diagnostics.Process应用程序中的类创建新流程。

我希望当我的应用程序崩溃时,该进程被终止。但是,如果我从任务管理器中杀死我的应用程序,则不会杀死子进程。

有什么方法可以使子进程依赖于父进程?

Answers:


176

此论坛中,将其归功于“ Josh”。

Application.Quit()并且Process.Kill()是可能的解决方案,但已证明是不可靠的。当主应用程序死亡时,您仍然可以运行子进程。我们真正想要的是子进程在主进程死亡后立即死亡。

解决方案是使用“作业对象” http://msdn.microsoft.com/zh-cn/library/ms682409(VS.85).aspx

这个想法是为您的主应用程序创建一个“作业对象”,并向该作业对象注册子进程。如果主进程终止,则操作系统将负责终止子进程。

public enum JobObjectInfoType
{
    AssociateCompletionPortInformation = 7,
    BasicLimitInformation = 2,
    BasicUIRestrictions = 4,
    EndOfJobTimeInformation = 6,
    ExtendedLimitInformation = 9,
    SecurityLimitInformation = 5,
    GroupInformation = 11
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
    public int nLength;
    public IntPtr lpSecurityDescriptor;
    public int bInheritHandle;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
    public Int64 PerProcessUserTimeLimit;
    public Int64 PerJobUserTimeLimit;
    public Int16 LimitFlags;
    public UInt32 MinimumWorkingSetSize;
    public UInt32 MaximumWorkingSetSize;
    public Int16 ActiveProcessLimit;
    public Int64 Affinity;
    public Int16 PriorityClass;
    public Int16 SchedulingClass;
}

[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
    public UInt64 ReadOperationCount;
    public UInt64 WriteOperationCount;
    public UInt64 OtherOperationCount;
    public UInt64 ReadTransferCount;
    public UInt64 WriteTransferCount;
    public UInt64 OtherTransferCount;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
    public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
    public IO_COUNTERS IoInfo;
    public UInt32 ProcessMemoryLimit;
    public UInt32 JobMemoryLimit;
    public UInt32 PeakProcessMemoryUsed;
    public UInt32 PeakJobMemoryUsed;
}

public class Job : IDisposable
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr CreateJobObject(object a, string lpName);

    [DllImport("kernel32.dll")]
    static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

    private IntPtr m_handle;
    private bool m_disposed = false;

    public Job()
    {
        m_handle = CreateJobObject(null, null);

        JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
        info.LimitFlags = 0x2000;

        JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
        extendedInfo.BasicLimitInformation = info;

        int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
        IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
        Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

        if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
            throw new Exception(string.Format("Unable to set information.  Error: {0}", Marshal.GetLastWin32Error()));
    }

    #region IDisposable Members

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion

    private void Dispose(bool disposing)
    {
        if (m_disposed)
            return;

        if (disposing) {}

        Close();
        m_disposed = true;
    }

    public void Close()
    {
        Win32.CloseHandle(m_handle);
        m_handle = IntPtr.Zero;
    }

    public bool AddProcess(IntPtr handle)
    {
        return AssignProcessToJobObject(m_handle, handle);
    }

}

看着构造函数...

JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
info.LimitFlags = 0x2000;

此处的关键是正确设置作业对象。在构造函数中,我将“限制”设置为0x2000,这是的数字值JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE

MSDN将该标志定义为:

当作业的最后一个句柄关闭时,导致与作业关联的所有进程终止。

设置好此类后,您只需在作业中注册每个子进程。例如:

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

Excel.Application app = new Excel.ApplicationClass();

uint pid = 0;
Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);
 job.AddProcess(Process.GetProcessById((int)pid).Handle);

4
我会添加一个指向CloseHandle
Austin Salonen

6
不幸的是,我无法在64位模式下运行它。在这里,我发布了一个基于此的工作示例。
亚历山大·叶祖托夫

2
@Matt Howells- Win32.CloseHandle起源于哪里?这是从kernel32.dll导入的吗?那里有一个匹配的签名,但是您没有像其他API函数一样显式导入它。
深奥的屏幕名称

6
对于64位应用程序模式- > stackoverflow.com/a/5976162对于Vista / Win7的问题- > social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/...
HB0

3
好的,MSDN说:JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE标志需要使用JOBOBJECT_EXTENDED_LIMIT_INFORMATION结构。
SerG 2014年

54

该答案以@Matt Howells的出色答案以及其他答案开头(请参见下面的代码中的链接)。改进之处:

  • 支持32位和64位。
  • 修复了@Matt Howells答案中的一些问题:
    1. 小内存泄漏 extendedInfoPtr
    2. “ Win32”编译错误,并且
    3. 我在调用中遇到了堆栈不平衡异常CreateJobObject(使用Windows 10,Visual Studio 2015、32位)。
  • 为作业命名,因此,例如,如果您使用SysInternals,则可以轻松找到它。
  • 具有较为简单的API和较少的代码。

这是使用此代码的方法:

// Get a Process object somehow.
Process process = Process.Start(exePath, args);
// Add the Process to ChildProcessTracker.
ChildProcessTracker.AddProcess(process);

要支持Windows 7,需要:

就我而言,我不需要支持Windows 7,因此我在下面的静态构造函数的顶部进行了简单的检查。

/// <summary>
/// Allows processes to be automatically killed if this parent process unexpectedly quits.
/// This feature requires Windows 8 or greater. On Windows 7, nothing is done.</summary>
/// <remarks>References:
///  https://stackoverflow.com/a/4657392/386091
///  https://stackoverflow.com/a/9164742/386091 </remarks>
public static class ChildProcessTracker
{
    /// <summary>
    /// Add the process to be tracked. If our current process is killed, the child processes
    /// that we are tracking will be automatically killed, too. If the child process terminates
    /// first, that's fine, too.</summary>
    /// <param name="process"></param>
    public static void AddProcess(Process process)
    {
        if (s_jobHandle != IntPtr.Zero)
        {
            bool success = AssignProcessToJobObject(s_jobHandle, process.Handle);
            if (!success && !process.HasExited)
                throw new Win32Exception();
        }
    }

    static ChildProcessTracker()
    {
        // This feature requires Windows 8 or later. To support Windows 7 requires
        //  registry settings to be added if you are using Visual Studio plus an
        //  app.manifest change.
        //  https://stackoverflow.com/a/4232259/386091
        //  https://stackoverflow.com/a/9507862/386091
        if (Environment.OSVersion.Version < new Version(6, 2))
            return;

        // The job name is optional (and can be null) but it helps with diagnostics.
        //  If it's not null, it has to be unique. Use SysInternals' Handle command-line
        //  utility: handle -a ChildProcessTracker
        string jobName = "ChildProcessTracker" + Process.GetCurrentProcess().Id;
        s_jobHandle = CreateJobObject(IntPtr.Zero, jobName);

        var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();

        // This is the key flag. When our process is killed, Windows will automatically
        //  close the job handle, and when that happens, we want the child processes to
        //  be killed, too.
        info.LimitFlags = JOBOBJECTLIMIT.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

        var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
        extendedInfo.BasicLimitInformation = info;

        int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
        IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
        try
        {
            Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

            if (!SetInformationJobObject(s_jobHandle, JobObjectInfoType.ExtendedLimitInformation,
                extendedInfoPtr, (uint)length))
            {
                throw new Win32Exception();
            }
        }
        finally
        {
            Marshal.FreeHGlobal(extendedInfoPtr);
        }
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string name);

    [DllImport("kernel32.dll")]
    static extern bool SetInformationJobObject(IntPtr job, JobObjectInfoType infoType,
        IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

    // Windows will automatically close any open job handles when our process terminates.
    //  This can be verified by using SysInternals' Handle utility. When the job handle
    //  is closed, the child processes will be killed.
    private static readonly IntPtr s_jobHandle;
}

public enum JobObjectInfoType
{
    AssociateCompletionPortInformation = 7,
    BasicLimitInformation = 2,
    BasicUIRestrictions = 4,
    EndOfJobTimeInformation = 6,
    ExtendedLimitInformation = 9,
    SecurityLimitInformation = 5,
    GroupInformation = 11
}

[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
    public Int64 PerProcessUserTimeLimit;
    public Int64 PerJobUserTimeLimit;
    public JOBOBJECTLIMIT LimitFlags;
    public UIntPtr MinimumWorkingSetSize;
    public UIntPtr MaximumWorkingSetSize;
    public UInt32 ActiveProcessLimit;
    public Int64 Affinity;
    public UInt32 PriorityClass;
    public UInt32 SchedulingClass;
}

[Flags]
public enum JOBOBJECTLIMIT : uint
{
    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
}

[StructLayout(LayoutKind.Sequential)]
public struct IO_COUNTERS
{
    public UInt64 ReadOperationCount;
    public UInt64 WriteOperationCount;
    public UInt64 OtherOperationCount;
    public UInt64 ReadTransferCount;
    public UInt64 WriteTransferCount;
    public UInt64 OtherTransferCount;
}

[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
    public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
    public IO_COUNTERS IoInfo;
    public UIntPtr ProcessMemoryLimit;
    public UIntPtr JobMemoryLimit;
    public UIntPtr PeakProcessMemoryUsed;
    public UIntPtr PeakJobMemoryUsed;
}

通过以编程方式将托管版本和本机版本相互比较(整体大小以及每个成员的偏移量),我仔细测试了结构的32位和64位版本。

我已经在Windows 7、8和10上测试了此代码。


关闭作业句柄怎么办?
Frank Q.

@FrankQ。让Windows在我们的进程终止时为我们关闭s_jobHandle是很重要的,因为我们的进程可能会意外终止(例如崩溃或用户使用任务管理器)。请参阅我对s_jobHandle的评论。
罗恩

它为我工作。请问您对使用JOB_OBJECT_LIMIT_BREAKAWAY_OK标志有何看法?docs.microsoft.com/zh-CN/windows/desktop/api/winnt/…–
Yiping

1
@yiping听起来像CREATE_BREAKAWAY_FROM_JOB允许您的子进程生成可以超过原始进程的进程。这是与OP要求不同的要求。相反,如果您可以使原始进程产生一个寿命更长的进程(而不使用ChildProcessTracker),那会更简单。
罗恩'18

@Ron您可以添加一个仅接受过程句柄而不接受整个过程的重载吗?
Jannik

47

这篇文章旨在作为@Matt Howells答案的扩展,特别是针对那些在Vista或Win7下使用Job Objects遇到问题的人,尤其是当您在调用AssignProcessToJobObject时遇到拒绝访问错误('5')时。

tl; dr

为了确保与Vista和Win7兼容,请将以下清单添加到.NET父进程中:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <v3:trustInfo xmlns:v3="urn:schemas-microsoft-com:asm.v3">
    <v3:security>
      <v3:requestedPrivileges>
        <v3:requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </v3:requestedPrivileges>
    </v3:security>
  </v3:trustInfo>
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <!-- We specify these, in addition to the UAC above, so we avoid Program Compatibility Assistant in Vista and Win7 -->
    <!-- We try to avoid PCA so we can use Windows Job Objects -->
    <!-- See https://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed -->

    <application>
      <!--The ID below indicates application support for Windows Vista -->
      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
      <!--The ID below indicates application support for Windows 7 -->
      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
    </application>
  </compatibility>
</assembly>

请注意,当您在Visual Studio 2012中添加新清单时,它将已经包含上面的代码段,因此您无需从听众那里复制它。它还将包括Windows 8的节点。

充分的解释

如果您正在启动的进程已经与另一个作​​业关联,则您的作业关联将失败,并显示访问被拒绝错误。输入程序兼容性助手,从Windows Vista开始,它将为自己的作业分配各种进程。

在Vista中,只需包含应用程序清单,就可以将您的应用程序标记为不包含在PCA中。Visual Studio似乎会自动为.NET应用程序执行此操作,因此您可以在其中使用。

一个简单的清单不再在Win7中删除它。[1]在这里,您必须使用清单中的标记专门指定与Win7兼容。[2]

这使我担心Windows8。是否需要再次更改清单?显然,云已经中断了,因为Windows 8现在允许一个进程属于多个作业。[3]因此,我尚未对其进行测试,但是我想,如果您仅在清单中包含所支持的OS信息,那么这种疯狂状态将会过去。

提示1:如果像我以前那样用Visual Studio开发.NET应用程序,这里[4]是一些有关如何自定义应用程序清单的很好的说明。

技巧2:从Visual Studio启动应用程序时要小心。我发现,添加适当的清单后,即使从Visual Studio启动时,即使使用了“不调试启动”,PCA仍然存在问题。但是,从资源管理器启动我的应用程序是可行的。使用注册表手动添加devenv以将其从PCA中排除之后,启动使用VS中的Job Objects的应用程序也开始工作。[5]

提示3:如果您想知道PCA是否是问题,请尝试从命令行启动应用程序,或将程序复制到网络驱动器并从那里运行。在这些情况下,将自动禁用PCA。

[1] http://blogs.msdn.com/b/cjacks/archive/2009/06/18/pca-changes-for-windows-7-how-to-tell-us-you-are-not-an安装程序采用2,因为我们更改了you.aspx上的规则

[2] http://ayende.com/blog/4360/how-to-opt-out-of-program-compatibility-assistant

[3] http://msdn.microsoft.com/zh-cn/library/windows/desktop/ms681949(v=vs.85).aspx:“一个进程可以与Windows 8中的多个作业相关联”

[4] 如何使用VS2008将应用程序清单嵌入到应用程序中?

[5] 如何停止Visual Studio调试器在作业对象中启动进程?


2
这些都是该主题的重要补充,谢谢!我利用了这个答案的各个方面,包括链接。
约翰尼·考夫曼

16

当您控制子进程运行的代码时,这是一种可行的替代方法。这种方法的好处是不需要任何本地Windows调用。

基本思想是将孩子的标准输入重定向到另一端连接到父级的流,并使用该流检测父级何时离开。当您使用System.Diagnostics.Process启动子,很容易保证它的标准输入重定向:

Process childProcess = new Process();
childProcess.StartInfo = new ProcessStartInfo("pathToConsoleModeApp.exe");
childProcess.StartInfo.RedirectStandardInput = true;

childProcess.StartInfo.CreateNoWindow = true; // no sense showing an empty black console window which the user can't input into

然后,在子进程上,利用以下事实:Read标准输入流中的s将始终返回至少1个字节,直到流关闭为止,此时它们将开始返回0个字节。我结束操作的方式概述如下:我的方法还使用消息泵来使主线程保持可用状态,而不是监视标准线程,但是这种通用方法也可以在没有消息泵的情况下使用。

using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

static int Main()
{
    Application.Run(new MyApplicationContext());
    return 0;
}

public class MyApplicationContext : ApplicationContext
{
    private SynchronizationContext _mainThreadMessageQueue = null;
    private Stream _stdInput;

    public MyApplicationContext()
    {
        _stdInput = Console.OpenStandardInput();

        // feel free to use a better way to post to the message loop from here if you know one ;)    
        System.Windows.Forms.Timer handoffToMessageLoopTimer = new System.Windows.Forms.Timer();
        handoffToMessageLoopTimer.Interval = 1;
        handoffToMessageLoopTimer.Tick += new EventHandler((obj, eArgs) => { PostMessageLoopInitialization(handoffToMessageLoopTimer); });
        handoffToMessageLoopTimer.Start();
    }

    private void PostMessageLoopInitialization(System.Windows.Forms.Timer t)
    {
        if (_mainThreadMessageQueue == null)
        {
            t.Stop();
            _mainThreadMessageQueue = SynchronizationContext.Current;
        }

        // constantly monitor standard input on a background thread that will
        // signal the main thread when stuff happens.
        BeginMonitoringStdIn(null);

        // start up your application's real work here
    }

    private void BeginMonitoringStdIn(object state)
    {
        if (SynchronizationContext.Current == _mainThreadMessageQueue)
        {
            // we're already running on the main thread - proceed.
            var buffer = new byte[128];

            _stdInput.BeginRead(buffer, 0, buffer.Length, (asyncResult) =>
                {
                    int amtRead = _stdInput.EndRead(asyncResult);

                    if (amtRead == 0)
                    {
                        _mainThreadMessageQueue.Post(new SendOrPostCallback(ApplicationTeardown), null);
                    }
                    else
                    {
                        BeginMonitoringStdIn(null);
                    }
                }, null);
        }
        else
        {
            // not invoked from the main thread - dispatch another call to this method on the main thread and return
            _mainThreadMessageQueue.Post(new SendOrPostCallback(BeginMonitoringStdIn), null);
        }
    }

    private void ApplicationTeardown(object state)
    {
        // tear down your application gracefully here
        _stdInput.Close();

        this.ExitThread();
    }
}

注意此方法:

  1. 实际启动的子.exe必须是控制台应用程序,因此它仍附加到stdin / out / err。如以上示例所示,我只需创建一个引用现有项目的小型控制台项目,实例化我的应用程序上下文并Application.Run()在该Main方法的内部调用,即可轻松地修改使用消息泵(但未显示GUI)的现有应用程序。控制台.exe。

  2. 从技术上讲,这仅在父进程退出时向子进程发出信号,因此无论父进程正常退出还是崩溃,它都将起作用,但仍由子进程自行执行关闭操作。这可能不是您想要的...


11

一种方法是将父进程的PID传递给子进程。子进程将定期轮询具有指定pid的进程是否存在。如果没有,它将退出。

您还可以在子方法中使用Process.WaitForExit方法,以在父过程结束时收到通知,但在任务管理器中可能无法正常工作。


如何将父级PID传递给子级?有什么系统解决方案?我无法修改子进程二进制文件。
SiberianGuy 2010年

1
好吧,如果您不能修改子进程,即使将PID传递给它,也无法使用我的解决方案。
Giorgi

@Idsa您可以通过命令行传递它:Process.Start(string fileName, string arguments)
Distortum 2012年

2
除了轮询之外,您还可以插入流程类的Exit事件。
RichardOD 2012年

尝试过它,但是如果子进程还活着(至少在我的情况下为Cobol-> NET),父进程并不总是退出。在Sysinternals ProcessExplorer中易于检查流程层次结构。
伊万·费雷尔

8

还有另一种简单有效的相关方法,可以在程序终止时完成子进程。您可以从父级实现调试器并将其附加到调试器。当父进程结束时,子进程将被操作系统杀死。将调试器从子级附加到父级有两种方法(请注意,一次只能附加一个调试器)。您可以在此处找到有关此主题的更多信息。

在这里,您有一个实用程序类,可以启动一个新进程并将调试器附加到该进程。它已根据Roger Knapp的帖子改编。唯一的要求是两个进程需要共享相同的位。您不能从64位进程调试32位进程,反之亦然。

public class ProcessRunner
{
    #region "API imports"

    private const int DBG_CONTINUE = 0x00010002;
    private const int DBG_EXCEPTION_NOT_HANDLED = unchecked((int) 0x80010001);

    private enum DebugEventType : int
    {
        CREATE_PROCESS_DEBUG_EVENT = 3,
        //Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure.
        CREATE_THREAD_DEBUG_EVENT = 2,
        //Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure.
        EXCEPTION_DEBUG_EVENT = 1,
        //Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure.
        EXIT_PROCESS_DEBUG_EVENT = 5,
        //Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure.
        EXIT_THREAD_DEBUG_EVENT = 4,
        //Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure.
        LOAD_DLL_DEBUG_EVENT = 6,
        //Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure.
        OUTPUT_DEBUG_STRING_EVENT = 8,
        //Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure.
        RIP_EVENT = 9,
        //Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure.
        UNLOAD_DLL_DEBUG_EVENT = 7,
        //Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure.
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct DEBUG_EVENT
    {
        [MarshalAs(UnmanagedType.I4)] public DebugEventType dwDebugEventCode;
        public int dwProcessId;
        public int dwThreadId;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)] public byte[] bytes;
    }

    [DllImport("Kernel32.dll", SetLastError = true)]
    private static extern bool DebugActiveProcess(int dwProcessId);

    [DllImport("Kernel32.dll", SetLastError = true)]
    private static extern bool WaitForDebugEvent([Out] out DEBUG_EVENT lpDebugEvent, int dwMilliseconds);

    [DllImport("Kernel32.dll", SetLastError = true)]
    private static extern bool ContinueDebugEvent(int dwProcessId, int dwThreadId, int dwContinueStatus);

    [DllImport("Kernel32.dll", SetLastError = true)]
    public static extern bool IsDebuggerPresent();

    #endregion

    public Process ChildProcess { get; set; }

    public bool StartProcess(string fileName)
    {
        var processStartInfo = new ProcessStartInfo(fileName)
        {
            UseShellExecute = false,
            WindowStyle = ProcessWindowStyle.Normal,
            ErrorDialog = false
        };

        this.ChildProcess = Process.Start(processStartInfo);
        if (ChildProcess == null)
            return false;

        new Thread(NullDebugger) {IsBackground = true}.Start(ChildProcess.Id);
        return true;
    }

    private void NullDebugger(object arg)
    {
        // Attach to the process we provided the thread as an argument
        if (DebugActiveProcess((int) arg))
        {
            var debugEvent = new DEBUG_EVENT {bytes = new byte[1024]};
            while (!this.ChildProcess.HasExited)
            {
                if (WaitForDebugEvent(out debugEvent, 1000))
                {
                    // return DBG_CONTINUE for all events but the exception type
                    var continueFlag = DBG_CONTINUE;
                    if (debugEvent.dwDebugEventCode == DebugEventType.EXCEPTION_DEBUG_EVENT)
                        continueFlag = DBG_EXCEPTION_NOT_HANDLED;
                    ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, continueFlag);
                }
            }
        }
        else
        {
            //we were not able to attach the debugger
            //do the processes have the same bitness?
            //throw ApplicationException("Unable to attach debugger") // Kill child? // Send Event? // Ignore?
        }
    }
}

用法:

    new ProcessRunner().StartProcess("c:\\Windows\\system32\\calc.exe");

8

我一直在寻找不需要非托管代码的解决方案。我还不能使用标准的输入/输出重定向,因为它是Windows Forms应用程序。

我的解决方案是在父进程中创建一个命名管道,然后将子进程连接到同一管道。如果父进程退出,则管道将断开,子进程可以检测到。

下面是使用两个控制台应用程序的示例:

父母

private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529";

public static void Main(string[] args)
{
    Console.WriteLine("Main program running");

    using (NamedPipeServerStream pipe = new NamedPipeServerStream(PipeName, PipeDirection.Out))
    {
        Process.Start("child.exe");

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

儿童

private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529"; // same as parent

public static void Main(string[] args)
{
    Console.WriteLine("Child process running");

    using (NamedPipeClientStream pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
    {
        pipe.Connect();
        pipe.BeginRead(new byte[1], 0, 1, PipeBrokenCallback, pipe);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

private static void PipeBrokenCallback(IAsyncResult ar)
{
    // the pipe was closed (parent process died), so exit the child process too

    try
    {
        NamedPipeClientStream pipe = (NamedPipeClientStream)ar.AsyncState;
        pipe.EndRead(ar);
    }
    catch (IOException) { }

    Environment.Exit(1);
}

3

使用事件处理程序在一些退出方案上建立钩子:

var process = Process.Start("program.exe");
AppDomain.CurrentDomain.DomainUnload += (s, e) => { process.Kill(); process.WaitForExit(); };
AppDomain.CurrentDomain.ProcessExit += (s, e) => { process.Kill(); process.WaitForExit(); };
AppDomain.CurrentDomain.UnhandledException += (s, e) => { process.Kill(); process.WaitForExit(); };

如此简单却如此有效。
uncommon_name

2

只是我的2018版本。在Main()方法旁边使用它。

    using System.Management;
    using System.Diagnostics;

    ...

    // Called when the Main Window is closed
    protected override void OnClosed(EventArgs EventArgs)
    {
        string query = "Select * From Win32_Process Where ParentProcessId = " + Process.GetCurrentProcess().Id;
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
        ManagementObjectCollection processList = searcher.Get();
        foreach (var obj in processList)
        {
            object data = obj.Properties["processid"].Value;
            if (data != null)
            {
                // retrieve the process
                var childId = Convert.ToInt32(data);
                var childProcess = Process.GetProcessById(childId);

                // ensure the current process is still live
                if (childProcess != null) childProcess.Kill();
            }
        }
        Environment.Exit(0);
    }

4
我怀疑在杀死父进程时会执行此操作。
springy76 '18 -10-30

1

我看到两个选择:

  1. 如果您确切知道可以启动哪个子进程,并且确定它们只是从主进程启动的,那么您可以考虑简单地按名称搜索它们并杀死它们。
  2. 遍历所有进程并杀死将您的进程作为父进程的每个进程(我想您需要先杀死子进程)。这里说明了如何获取父进程ID。


0

在流程开始后最好调用job.AddProcess来做:

prc.Start();
job.AddProcess(prc.Handle);

在终止之前调用AddProcess时,不会终止子进程。(Windows 7 SP1)

private void KillProcess(Process proc)
{
    var job = new Job();
    job.AddProcess(proc.Handle);
    job.Close();
}

在该过程开始后调用job.AddProcess将终止使用此对象的目的。
SerG 2014年

0

到目前为止,对解决方案的丰富性提出了又一个补充。

它们中的许多问题在于,它们依赖于父子进程有序地关闭,这在开发正在进行时并不总是正确的。我发现,每当我在调试器中终止父进程时,我的子进程就经常被孤立,这要求我使用任务管理器杀死孤立的进程以重建解决方案。

解决方案:在子进程的命令行上传递父进程ID(或者在环境变量中侵入性更小)。

在父流程中,该流程ID可用为:

  Process.CurrentProcess.Id;

在子进程中:

Process parentProcess = Process.GetProcessById(parentProcessId);
parentProcess.Exited += (s, e) =>
{
    // clean up what you can.
    this.Dispose();
    // maybe log an error
    ....

    // And terminate with prejudice! 
    //(since something has already gone terribly wrong)
    Process.GetCurrentProcess().Kill();
}

关于这在生产代码中是否可以接受,我有两种想法。一方面,这永远都不会发生。但另一方面,这可能意味着重新启动进程和重新启动生产服务器之间的区别。而且永远不会发生的事情经常发生。

并且在调试有序关闭问题时肯定有用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.