Repository navigation
Closed
Labels
Milestone
Description
Description
When programmatically sending Ctrl+C command to shut down another program, Host.Dispose() gives the following exception:
at System.Runtime.InteropServices.PosixSignalRegistration.Unregister()
at System.Runtime.InteropServices.PosixSignalRegistration.Dispose()
at Microsoft.Extensions.Hosting.Internal.ConsoleLifetime.UnregisterShutdownHandlers()
at Microsoft.Extensions.Hosting.Internal.ConsoleLifetime.Dispose()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.DisposeAsync()
--- End of stack trace from previous location ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter.GetResult()
at Microsoft.Extensions.Hosting.Internal.Host.<<DisposeAsync>g__DisposeAsync|16_0>d.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter.GetResult()
at Microsoft.Extensions.Hosting.Internal.Host.<DisposeAsync>d__16.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.Extensions.Hosting.Internal.Host.Dispose()
at CtrlCServer.Program.Main(String[] args) in C:\...\Program.cs
Reproduction Steps
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static class NativeMethods
{
public enum CtrlType : uint
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
}
public delegate bool ConsoleCtrlDelegate(CtrlType ctrlType);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate? handlerRoutine, bool add);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GenerateConsoleCtrlEvent(CtrlType dwCtrlEvent, uint dwProcessGroupId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool AttachConsole(uint dwProcessId);
[DllImport("kernel32.dll")]
public static extern bool FreeConsole();
public static int Signal(int processId)
{
FreeConsole();
var process = Process.GetProcessById(processId);
if (!AttachConsole(checked((uint)processId)))
{
throw new Exception();
}
if (!SetConsoleCtrlHandler(null, true))
{
throw new Exception();
}
if (!GenerateConsoleCtrlEvent(CtrlType.CTRL_C_EVENT, 0))
{
throw new Exception();
}
process.WaitForExit();
if (!FreeConsole())
{
throw new Exception();
}
if (!SetConsoleCtrlHandler(null, false))
{
throw new Exception();
}
return 0;
}
}
class Program
{
static void Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args).Build();
host.Start();
var processes = Process.GetProcessesByName("any-process");
foreach (var p in processes)
{
if (p.Threads.Count > 0)
{
NativeMethods.Signal(p.Id);
}
}
host.Dispose(); // System.IO.IOException “The parameter is incorrect”
}
}Expected behavior
host should be disposed successfully.
Actual behavior
host can't be disposed. An exception is thrown.
Regression?
.netcore 3.1.x has this issue as well.
Known Workarounds
No response
Configuration
Windows 10 20H2 x64;
.netcore sdk 3.1.415 x64;
.net sdk 6.0.100 x64
Other information
Related issue: #21726
Activity
eerhardt commentedon Nov 30, 2021
The issue here is that you are calling
FreeConsole()(andAttachConsole). See https://docs.microsoft.com/en-us/windows/console/setconsolectrlhandler#remarksSince this is removing our console ctrl handler, when we try disposing the
PosixSignalRegistrationan exception is getting thrown since we are trying to remove it from Windows:runtime/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Windows.cs
Lines 53 to 57 in b1b7ad4
@stephentoub - one option I see here is to ignore the error in
PosixSignalRegistration.Unregister()if we get back "this handler isn't registered" error.The other option I see here is to just live with this behavior. If the calling app needs/wants to call
AttachConsole/FreeConsole, then they need to use a different hosting Lifetime that works with these APIs.Are there other ways of sending signals to processes on Windows that don't involve calling
AttachConsole/FreeConsole?cc @davidfowl
stephentoub commentedon Nov 30, 2021
Regardless of this particular issue, I think that's reasonable. Do we know the full list of errors possible from SetConsoleCtrlHandler? We might even just ignore them all, as long as the handler would in fact no longer be registered after the call (e.g. if there were an error like "try again later", that would be a problem to ignore). Basically, as long as Unregister is successfully ensuring that the handler isn't registered once Unregister returns, we don't need to throw.
eerhardt commentedon Nov 30, 2021
I'm not seeing the list in the docs. 😞 It just says:
From debugging, I see that we are getting
E_INVALIDARGback from the call. Since there are only 2 args, and one of them is a BOOL, we can assume the invalid arg is the first arg - the handler. And since we are passingFALSEin forAdd, I think we can assume the handler is not in the list if we getE_INVALIDARGback.