A进程是系统进程,B进程是用户进程。如果A进程需要执行一个复杂的操作(需独立子进程完成),但需要在B的用户上下文中执行。
A进程的接受服务线程代码(需要快速的取消息,并分发到子进程)
809 boost::shared_ptr<void>
810 ImpersonateAndGetThreadToken()
811 {
812 boost::shared_ptr<void> threadToken;
813 HANDLE rawToken;
814
815 if(!ImpersonateNamedPipeClient(XXXX->GetHandle())) {
816 wxLogSysError(wxT("Failed to impersonate client to get the user's thread token"));
817 return threadToken;
818 }
819
820 if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_IMPERSONATE, FALSE, &rawToken)) {
821 threadToken.reset(rawToken, &::CloseHandle);
822 } else {
823 wxLogSysError(wxT("Failed to open the user's thread token"));
824 }
825
826 if(!RevertToSelf()) {
827 wxLogSysError(wxT("Failed to revert to self!!!"));
828 TerminateProcess(GetCurrentProcess(), GetLastError());
829 }
830
831 return threadToken;
832 }
boost::shared_ptr<void> m_userThreadToken = ImpersonateAndGetThreadToken();
//newSubThread = new ThreadXXXX(m_userThreadToken);
newSubThread->Run();A进程的独立子进程代码
// boost::shared_ptr<void> m_userThreadToken;
SubThreadProc {
1513 if (m_userThreadToken.get() == NULL)
1514 {
1515 wxLogSysError(wxT("No thread token!"));
1516 return false;
1517 }
1518
1519 if (!ImpersonateLoggedOnUser(m_userThreadToken.get()))
1520 {
1521 wxLogSysError(wxT("Failed to impersonate the caller's context!"));
1522 return false;
1523 }
1524
//Your complicated code logic here.
1541
1542 if(!RevertToSelf())
1543 {
1544 wxLogSysError(wxT("Failed to revert to self!!!"));
1545 return false;
1546 }
1547
1549 }
及时的RevertToSelf很重要,以免出现安全漏洞。