我有打开子进程的父进程。只有当父进程不再运行时,我才需要执行一些功能。
了解父进程未运行的最佳方法是什么?因为它可以被暴力终止,所以我不想做一些会在关闭事件时向我的子进程发送信号的功能。
或者只是像那样寻找我的父进程:
在父级中创建并传递给子级 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/