【问题标题】:Shutdown.exe is not shutting down system immediately, why?Shutdown.exe 没有立即关闭系统,为什么?
【发布时间】:2014-02-27 03:45:12
【问题描述】:

我正在使用System.Diagnostics.Process.Start("shutdown.exe", "-r -f -t 1") 重新启动服务器。直到最近我注意到server(win xp) 没有立即关闭时,它一直运行良好。我的日志显示应用程序在shutdown.exe 命令后至少运行 60 秒。

所以我开始怀疑shutdown.exe 是否有任何原因/条件/等无法关闭系统,即使使用了 -f。

【问题讨论】:

    标签: c# window system-shutdown


    【解决方案1】:

    您可以call the API directly

    ,而不是调用可执行文件
    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public static extern bool InitiateSystemShutdownEx(
        string lpMachineName,
        string lpMessage,
        uint dwTimeout,
        bool bForceAppsClosed,
        bool bRebootAfterShutdown,
        uint dwReason);
    

    如果出现问题,异常应该会为您指明正确的方向。一方面,您必须拥有SeShutdownPrivilege,并且必须启用它。

    考虑到权限后,完整的代码应如下所示。注意:这里假设使用System.Security.AccessControl.Privelege 类,其中was released in an MSDN magazine article,可下载as linked from the article。

    Privilege.RunWithPrivilege(Privilege.Shutdown, true, (_) =>
    {
        if (!NativeMethods.InitiateSystemShutdownEx(null /* this computer */,
            "My application really needs to restart",
            30 /* seconds */, true /* force shutdown */,
            true /* restart */, 0x4001 /* application: unplanned maintenance */))
        {
            throw new Win32Exception();
        }
    }, null);
    

    这将执行与您通过调用 shutdown.exe 尝试执行的操作相同的功能,但最关键的是,如果存在任何阻止成功关闭的故障或安全限制,它将引发异常。

    【讨论】:

    • 不幸的是我的应用程序是窗口服务,我相信这个 API 只适用于桌面应用程序。
    • 这是advapi32 的一部分,绝对可以从服务中使用。 shutdown.exe 只是 InitiateSystemShutdownEx 的一个包装器。
    【解决方案2】:

    尝试使用斜线而不是破折号。 /r /f /t 1

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 2019-03-31
      • 2012-11-11
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2017-02-20
      相关资源
      最近更新 更多