重要紧急:一段关机重启的代码ShutDownMachine的执行结果不令人满意,请各位指教,来者有份,谢谢!!!
经过添加调试后的代码如下:
BOOL ShutDownMachine()
{
DebugLogFile( "Begin to ShutDownMachine! ");
TOKEN_PRIVILEGES tp;
LUID luid;
HANDLE hTokenHandle ;
HANDLE hProcess = NULL;
BOOL bSuccess;
DWORD dwLastError;
//get Token
hProcess = GetCurrentProcess();
bSuccess = OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hTokenHandle);
if (!bSuccess)
{
DebugLogFile( "OpenProcessToken,bSuccess == FALSE. ");
dwLastError = GetLastError();
return FALSE;
}
DebugLogFile( "Get Token success! ");
//get shut down luid
bSuccess = LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &luid);
if (!bSuccess)
{
DebugLogFile( "LookupPrivilegeValue,bSuccess == FALSE. ");
dwLastError = GetLastError();
return FALSE;
}
DebugLogFile( "Get shut down priviledge success! ");
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
//get shut down priviledge
bSuccess = AdjustTokenPrivileges(hTokenHandle, FALSE, &tp,
sizeof(TOKEN_PRIVILEGES), NULL, NULL);
if (!bSuccess)
{
DebugLogFile( "AdjustTokenPrivileges,bSuccess == FALSE. ");
dwLastError = GetLastError();
return FALSE;
}
DebugLogFile( "AdjustTokenPrivilege succeed! ");
//restart this computer
if (!ExitWindowsEx( EWX_REBOOT|EWX_FORCE, 0))
{
DebugLogFile( "ExitWindowsEx return fail. ");
dwLastError = GetLastError();
return FALSE;
}
DebugLogFile( "restart this computer succeed! ");
return TRUE;
}
上面的代码执行后,其实是尝试重启电脑的。但是一直不能成功,直到一段时间以后(这段时间并不固定,具体数据参下),才能完成电脑重启。下面的是用户使用中的统计结果(英文版WinXpSP1):
最长的一次从
2007-1-10 5:8:10 g_iTimeOut = 16.
2007-1-10 8:3:33 LookupPrivilegeValue,bSuccess == FALSE.
2007-1-10 8:4:35 LookupPrivilegeValue,bSuccess == FALSE.
历时将近3个小时。
电脑于8:06:07重启
2007-1-10 8:51:32 g_iTimeOut = 16.
2007-1-10 8:51:41 LookupPrivilegeValue,bSuccess == FALSE.
历时不到10秒。
电脑于8:52:32重启
最短的一次从
2007-1-10 16:8:6 g_iTimeOut = 16.
2007-1-10 16:8:14 LookupPrivilegeValue,bSuccess == FALSE.
历时仅仅8秒。
电脑于16:09:26重启
2007-1-10 20:7:3 g_iTimeOut = 16.
2007-1-10 20:7:13 LookupPrivilegeValue,bSuccess == FALSE.
历时10分钟。
电脑于20:08:09重启
而根据我电脑(中文WinXpSp2)的测试结果如下:
第一次:50秒
2007-1-13 14:34:53 g_iTimeOut = 16.
2007-1-13 14:35:42 LookupPrivilegeValue,bSuccess == FALSE.
第二次:11秒
2007-1-13 21:14:23 g_iTimeOut = 16.
2007-1-13 21:14:34