11// Licensed to the .NET Foundation under one or more agreements.
22// The .NET Foundation licenses this file to you under the MIT license.
33
4+ using System . Runtime . InteropServices ;
5+
46namespace Microsoft . AspNetCore . Hosting ;
57
68internal sealed class WebHostLifetime : IDisposable
@@ -9,22 +11,22 @@ internal sealed class WebHostLifetime : IDisposable
911 private readonly ManualResetEventSlim _resetEvent ;
1012 private readonly string _shutdownMessage ;
1113
14+ private readonly PosixSignalRegistration _sigIntRegistration ;
15+ private readonly PosixSignalRegistration _sigQuitRegistration ;
16+ private readonly PosixSignalRegistration _sigTermRegistration ;
17+
1218 private bool _disposed ;
13- private bool _exitedGracefully ;
1419
1520 public WebHostLifetime ( CancellationTokenSource cts , ManualResetEventSlim resetEvent , string shutdownMessage )
1621 {
1722 _cts = cts ;
1823 _resetEvent = resetEvent ;
1924 _shutdownMessage = shutdownMessage ;
2025
21- AppDomain . CurrentDomain . ProcessExit += ProcessExit ;
22- Console . CancelKeyPress += CancelKeyPress ;
23- }
24-
25- internal void SetExitedGracefully ( )
26- {
27- _exitedGracefully = true ;
26+ Action < PosixSignalContext > handler = HandlePosixSignal ;
27+ _sigIntRegistration = PosixSignalRegistration . Create ( PosixSignal . SIGINT , handler ) ;
28+ _sigQuitRegistration = PosixSignalRegistration . Create ( PosixSignal . SIGQUIT , handler ) ;
29+ _sigTermRegistration = PosixSignalRegistration . Create ( PosixSignal . SIGTERM , handler ) ;
2830 }
2931
3032 public void Dispose ( )
@@ -35,26 +37,18 @@ public void Dispose()
3537 }
3638
3739 _disposed = true ;
38- AppDomain . CurrentDomain . ProcessExit -= ProcessExit ;
39- Console . CancelKeyPress -= CancelKeyPress ;
40- }
4140
42- private void CancelKeyPress ( object ? sender , ConsoleCancelEventArgs eventArgs )
43- {
44- Shutdown ( ) ;
45- // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
46- eventArgs . Cancel = true ;
41+ _sigIntRegistration . Dispose ( ) ;
42+ _sigQuitRegistration . Dispose ( ) ;
43+ _sigTermRegistration . Dispose ( ) ;
4744 }
4845
49- private void ProcessExit ( object ? sender , EventArgs eventArgs )
46+ private void HandlePosixSignal ( PosixSignalContext context )
5047 {
5148 Shutdown ( ) ;
52- if ( _exitedGracefully )
53- {
54- // On Linux if the shutdown is triggered by SIGTERM then that's signaled with the 143 exit code.
55- // Suppress that since we shut down gracefully. https://github.com/dotnet/aspnetcore/issues/6526
56- Environment . ExitCode = 0 ;
57- }
49+
50+ // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
51+ context . Cancel = true ;
5852 }
5953
6054 private void Shutdown ( )
0 commit comments