我有3个流程(祖父母,父母和子女)。祖父母(Grandparent)是守护程序,它调用Parent.exe,而后者又调用Child.exe。当我从任务管理器中杀死Parent.exe时,Child.exe继续存在,并且祖父母没有立即获得该控件。仅在Child.exe完成执行后,祖父母才能获得控制权。
但是,如果我做任何其他工作,则不是从Parent.exe调用Child.exe,而是当Parent.exe从任务管理器中被杀死时,GrandParent会立即获得控制权。
为什么在第一种情况下控件没有立即通过?我应该怎么做才能实现它?
我尝试同时使用Medallion.Shell和System.Diagonostics.Process.Process来调用父级和子级可执行文件。
GrandParent
static void Main(string[] args)
{
Console.WriteLine("Grand Parent Started");
try
{
while (Console.ReadKey() != null)
{
var childExePath = @"Child.exe";
var parentExePath = @"Parent.exe";
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = parentExePath,
Arguments = childExePath,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
RedirectStandardError = true
}
};
proc.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
proc.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
proc.Start();
Console.WriteLine($"{DateTime.Now:O} Starting Parent.exe - {proc.Id}");
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
Console.WriteLine($"{DateTime.Now:O} Stopping Parent.exe - {proc.Id}");
}
}
catch (Exception ex)
{
Console.WriteLine($"{DateTime.Now:O} Exception in GrandParent - {ex}");
}
}
父母
static void Main(string[] args)
{
try
{
Console.WriteLine($"{DateTime.Now:O} Parent Started");
Task.Run(() =>
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = args[0],
Arguments = "Parent",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
RedirectStandardError = true
}
};
proc.Start();
proc.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
proc.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
Console.WriteLine($"{DateTime.Now:O} Starting Child.exe: {proc.Id.ToString()}");
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
Console.WriteLine($"{DateTime.Now:O} Stopping Child.exe: {proc.Id.ToString()}");
});
Console.WriteLine($"{DateTime.Now:O} Parent Ended");
}
catch (Exception ex)
{
Console.WriteLine($"{DateTime.Now:O} Execption caught in Parent - {ex.Message}");
Console.ReadKey();
}
}
孩子
static void Main(string[] args)
{
var name = args != null && args.Length > 0 ? args[0] : "Test";
int i = 0;
while (i < 50)
{
var msg = string.Format("{0}::Hello World({2})-{1}", DateTime.Now.ToString("O"), name, i);
Console.WriteLine(msg);
Thread.Sleep(1000);
i++;
}
}