父进程与子进程关系

Nig*_*ker 4 .net c# process

我有打开子进程的父进程。仅当父进程不再运行时,我才需要执行某些功能。

知道父进程没有运行的最佳方法是什么?因为它可以被暴力终止,所以我不想创建一些在关闭事件时向我的子进程发送信号的功能。

或者只是寻找我的父进程,如下所示:

在父进程中创建这个并将其传递给子进程 Process.GetCurrentProcess().Id 并在子进程中每隔几毫秒检查一次

Process localById = Process.GetProcessById(1234);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?建议..

Dir*_*mar 5

下面是一个简单的示例,如何使用Process.WaitForExit它来检查 id 已在命令行上传递的父进程:

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static AutoResetEvent _autoResetEvent;

    static void Main(string[] args)
    {
        int parentProcessId = int.Parse(args[0]);

        _autoResetEvent = new AutoResetEvent(false);

        WaitCallback callback = delegate(object processId) { CheckProcess((int)processId); };
        ThreadPool.QueueUserWorkItem(callback, parentProcessId);

        _autoResetEvent.WaitOne();
    }

    static void CheckProcess(int processId)
    {
        try
        {
            Process process = Process.GetProcessById(processId);
            process.WaitForExit();
            Console.WriteLine("Process [{0}] exited.", processId);
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Process [{0}] not running.", processId);
        }

        _autoResetEvent.Set();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Process.Exited事件可以这样完成:

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static AutoResetEvent _autoResetEvent;

    static void Main(string[] args)
    {
        int parentProcessId = int.Parse(args[0]);
        Process process = Process.GetProcessById(parentProcessId);
        process.EnableRaisingEvents = true;
        process.Exited += new EventHandler(process_Exited);

        _autoResetEvent = new AutoResetEvent(false);
        _autoResetEvent.WaitOne();
    }

    static void process_Exited(object sender, EventArgs e)
    {
        Console.WriteLine("Process exit event triggered.");
        _autoResetEvent.Set();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在这两个示例中, 的目的AutoResetEvent只是为了防止主线程退出。在 Windows 窗体应用程序中,您不需要使用它,因为您的程序将处于消息循环中,只有在关闭它时才会退出。