Skip to content

Commit 5299c59

Browse files
Copilotnohwnd
andcommitted
Add SIGTERM signal handling to CTRLPlusCCancellationTokenSource
Co-authored-by: nohwnd <5735905+nohwnd@users.noreply.github.com>
1 parent 539a22c commit 5299c59

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/Platform/Microsoft.Testing.Platform/Services/CTRLPlusCCancellationTokenSource.cs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ internal sealed class CTRLPlusCCancellationTokenSource : ITestApplicationCancell
1111
private readonly CancellationTokenSource _cancellationTokenSource = new();
1212
private readonly ILogger? _logger;
1313

14+
#if NETCOREAPP
15+
private PosixSignalRegistration? _sigTermRegistration;
16+
#endif
17+
1418
public CTRLPlusCCancellationTokenSource(IConsole? console = null, ILogger? logger = null)
1519
{
1620
if (console is not null && !IsCancelKeyPressNotSupported())
@@ -19,7 +23,38 @@ public CTRLPlusCCancellationTokenSource(IConsole? console = null, ILogger? logge
1923
}
2024

2125
_logger = logger;
26+
27+
#if NETCOREAPP
28+
// Register for SIGTERM signals if not running on WASI
29+
if (!OperatingSystem.IsWasi())
30+
{
31+
try
32+
{
33+
_sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandlePosixSignal);
34+
}
35+
catch (Exception ex)
36+
{
37+
_logger?.LogWarning($"Failed to register SIGTERM signal handler: {ex}");
38+
}
39+
}
40+
#endif
41+
}
42+
43+
#if NETCOREAPP
44+
private void HandlePosixSignal(PosixSignalContext context)
45+
{
46+
context.Cancel = true;
47+
try
48+
{
49+
_cancellationTokenSource.Cancel();
50+
_logger?.LogInformation("Received SIGTERM signal, cancellation requested.");
51+
}
52+
catch (AggregateException ex)
53+
{
54+
_logger?.LogWarning($"Exception during SIGTERM signal handling:\n{ex}");
55+
}
2256
}
57+
#endif
2358

2459
[SupportedOSPlatformGuard("android")]
2560
[SupportedOSPlatformGuard("ios")]
@@ -51,7 +86,12 @@ private void OnConsoleCancelKeyPressed(object? sender, ConsoleCancelEventArgs e)
5186
}
5287

5388
public void Dispose()
54-
=> _cancellationTokenSource.Dispose();
89+
{
90+
#if NETCOREAPP
91+
_sigTermRegistration?.Dispose();
92+
#endif
93+
_cancellationTokenSource.Dispose();
94+
}
5595

5696
public void Cancel()
5797
=> _cancellationTokenSource.Cancel();

0 commit comments

Comments
 (0)