我正在应用程序中使用System.Diagnostics.Process
类创建新进程。
当我的应用程序崩溃时,我希望这个进程被终止。但是如果我从任务管理器中杀死我的应用程序,子进程不会被杀死。
有没有办法使子进程依赖于父进程?
发布于 2010-07-27 19:09:28
一种方法是将父进程的PID传递给子进程。子进程将定期轮询具有指定pid的进程是否存在。如果不是,它就会退出。
您还可以在子方法中使用Process.WaitForExit方法,以便在父进程结束时收到通知,但在任务管理器的情况下可能不起作用。
发布于 2017-06-08 17:40:46
我正在寻找一种不需要非托管代码的解决方案。我也无法使用标准的输入/输出重定向,因为它是一个Windows窗体应用程序。
我的解决方案是在父进程中创建一个命名管道,然后将子进程连接到同一管道。如果父进程退出,则管道中断,子进程可以检测到这一点。
下面是使用两个控制台应用程序的示例:
父级
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);
}
发布于 2018-10-28 21:39:45
只是我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);
}
https://stackoverflow.com/questions/3342941
复制相似问题