1
1
// Licensed to the .NET Foundation under one or more agreements.
2
2
// The .NET Foundation licenses this file to you under the MIT license.
3
3
4
+ using System . Runtime . InteropServices ;
5
+
4
6
namespace Microsoft . AspNetCore . Hosting ;
5
7
6
8
internal sealed class WebHostLifetime : IDisposable
@@ -9,22 +11,22 @@ internal sealed class WebHostLifetime : IDisposable
9
11
private readonly ManualResetEventSlim _resetEvent ;
10
12
private readonly string _shutdownMessage ;
11
13
14
+ private PosixSignalRegistration _sigIntRegistration ;
15
+ private PosixSignalRegistration _sigQuitRegistration ;
16
+ private PosixSignalRegistration _sigTermRegistration ;
17
+
12
18
private bool _disposed ;
13
- private bool _exitedGracefully ;
14
19
15
20
public WebHostLifetime ( CancellationTokenSource cts , ManualResetEventSlim resetEvent , string shutdownMessage )
16
21
{
17
22
_cts = cts ;
18
23
_resetEvent = resetEvent ;
19
24
_shutdownMessage = shutdownMessage ;
20
25
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 ) ;
28
30
}
29
31
30
32
public void Dispose ( )
@@ -35,26 +37,18 @@ public void Dispose()
35
37
}
36
38
37
39
_disposed = true ;
38
- AppDomain . CurrentDomain . ProcessExit -= ProcessExit ;
39
- Console . CancelKeyPress -= CancelKeyPress ;
40
- }
41
40
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 ( ) ;
47
44
}
48
45
49
- private void ProcessExit ( object ? sender , EventArgs eventArgs )
46
+ private void HandlePosixSignal ( PosixSignalContext context )
50
47
{
51
48
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 ;
58
52
}
59
53
60
54
private void Shutdown ( )
0 commit comments