diff --git a/src/Platform/Microsoft.Testing.Platform/Services/CTRLPlusCCancellationTokenSource.cs b/src/Platform/Microsoft.Testing.Platform/Services/CTRLPlusCCancellationTokenSource.cs index 3521080157..7d8ed15018 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/CTRLPlusCCancellationTokenSource.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/CTRLPlusCCancellationTokenSource.cs @@ -11,6 +11,10 @@ internal sealed class CTRLPlusCCancellationTokenSource : ITestApplicationCancell private readonly CancellationTokenSource _cancellationTokenSource = new(); private readonly ILogger? _logger; +#if NETCOREAPP + private PosixSignalRegistration? _sigTermRegistration; +#endif + public CTRLPlusCCancellationTokenSource(IConsole? console = null, ILogger? logger = null) { if (console is not null && !IsCancelKeyPressNotSupported()) @@ -19,7 +23,38 @@ public CTRLPlusCCancellationTokenSource(IConsole? console = null, ILogger? logge } _logger = logger; + +#if NETCOREAPP + // Register for SIGTERM signals if not running on WASI + if (!OperatingSystem.IsWasi()) + { + try + { + _sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandlePosixSignal); + } + catch (Exception ex) + { + _logger?.LogWarning($"Failed to register SIGTERM signal handler: {ex}"); + } + } +#endif + } + +#if NETCOREAPP + private void HandlePosixSignal(PosixSignalContext context) + { + context.Cancel = true; + try + { + _cancellationTokenSource.Cancel(); + _logger?.LogInformation("Received SIGTERM signal, cancellation requested."); + } + catch (AggregateException ex) + { + _logger?.LogWarning($"Exception during SIGTERM signal handling:\n{ex}"); + } } +#endif [SupportedOSPlatformGuard("android")] [SupportedOSPlatformGuard("ios")] @@ -51,7 +86,12 @@ private void OnConsoleCancelKeyPressed(object? sender, ConsoleCancelEventArgs e) } public void Dispose() - => _cancellationTokenSource.Dispose(); + { +#if NETCOREAPP + _sigTermRegistration?.Dispose(); +#endif + _cancellationTokenSource.Dispose(); + } public void Cancel() => _cancellationTokenSource.Cancel();