Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable termination of Hidi processes through pressing the breaking key combinations #1108

Merged
merged 7 commits into from
Dec 19, 2022
35 changes: 30 additions & 5 deletions src/Microsoft.OpenApi.Hidi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Hosting;
using System.CommandLine.Parsing;

using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Hidi.Handlers;

Expand All @@ -19,6 +17,9 @@ static class Program
{
static async Task Main(string[] args)
{
// subscribe to CancelKeyPress event to listen for termination requests from users through Ctrl+C or Ctrl+Break keys
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPressEvent);

var rootCommand = new RootCommand() {
};

Expand Down Expand Up @@ -127,5 +128,29 @@ static async Task Main(string[] args)
//// Wait for logger to write messages to the console before exiting
await Task.Delay(10);
}

/// <summary>
/// This event is raised when the user presses either of the two breaking key combinations: Ctrl+C or Ctrl+Break keys.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private static void Console_CancelKeyPressEvent(object sender, ConsoleCancelEventArgs eventArgs)
baywet marked this conversation as resolved.
Show resolved Hide resolved
{
if ((eventArgs.SpecialKey == ConsoleSpecialKey.ControlC) || (eventArgs.SpecialKey == ConsoleSpecialKey.ControlBreak))
{
Console.WriteLine("CTRL+C pressed, aborting current process...");
Thread.Sleep(5000);
MaggieKimani1 marked this conversation as resolved.
Show resolved Hide resolved

if (Process.GetCurrentProcess().HasExited)
{
Console.WriteLine("Process has already exited.");
}
else
{
Console.WriteLine("Process has not exited, attempting to kill process...");
Process.GetCurrentProcess().Kill();
}
}
}
}
}