the easiest is to redirect the console, and send an exit command,
How to terminate a process cleanly from a background service
I have developed a program which runs as a Windows service. This program starts a process to run another exe file. It's developed in C# with .NET 6.0.
I know I can use
Process.Kill()
to terminate the process, but I'd like to try to end the process cleanly before killing it. I've read through several other threads, but haven't found a solution that works. The exe file that is run as a process does not have a GUI, so CloseMainWindow doesn't work. Here is the code where I start the process. When a CancellationToken arrives, the loop exits and the service tries to end the exe process.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "otherprogram.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
bool exited = false;
while (!stoppingToken.IsCancellationRequested && !exited)
{
exited = exeProcess.WaitForExit(1000);
}
if (!exited)
{
exeProcess.CloseMainWindow(); // THIS DOES NOT WORK!!!!
exited = exeProcess.WaitForExit(5000);
}
if (!exited)
{
exeProcess.Kill();
exited = exeProcess.WaitForExit(5000);
}
}
Any suggestions or pointers to other threads would be greatly appreciated. Thank you!