c# - 父进程和子进程关系

标签 c# .net process

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

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

或者只是像那样寻找我的父进程:

在父级中创建并传递给子级 Process.GetCurrentProcess().Id 在 child 身上每隔几毫秒检查一次

Process localById = Process.GetProcessById(1234);

有什么想法吗?建议..

最佳答案

这是一个简单的例子,如何使用 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();
    }
}

使用 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();
    }
}

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

关于c# - 父进程和子进程关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3333048/

相关文章:

c# - 在 C++ 中序列化然后在 C# 中反序列化?

c# - 无法将数据从c#插入到mysql数据库

c# - 不知道任务数的进度条

.net - 基于 2d map 的瓦片游戏引擎

linux - linux进程的内存利用率

c# - 当我使用 Control-C 中断 C# 控制台应用程序时会发生什么?

c# - 任务取消

.net - Delphi 和 Delphi.NET 之间的区别

c# - 如何使用 C# 在命令提示符下更改目录位置?

linux - 如何在 Linux 中获取有关进程的信息