1
我正在製作一個像app一樣的taskmanager。對於windows,我可以得到所有的系統進程,現在我想獲取進程的用戶名。我從網上獲得了代碼。獲取進程用戶名C++
void enableDebugPrivileges()
{
HANDLE hcurrent=GetCurrentProcess();
HANDLE hToken;
BOOL bret=OpenProcessToken(hcurrent,40,&hToken);
LUID luid;
bret=LookupPrivilegeValue(NULL,SE_LOAD_DRIVER_NAME, &luid);
TOKEN_PRIVILEGES NewState,PreviousState;
DWORD ReturnLength;
NewState.PrivilegeCount =1;
NewState.Privileges[0].Luid =luid;
NewState.Privileges[0].Attributes=2;
AdjustTokenPrivileges(hToken,FALSE,&NewState,28,&PreviousState,&ReturnLength);
}
char *GetProcessUsername(HANDLE *phProcess, BOOL bIncDomain)
{
static char sname[300];
HANDLE tok = 0;
HANDLE hProcess;
TOKEN_USER *ptu;
DWORD nlen, dlen;
char name[300], dom[300], tubuf[300], *pret = 0;
int iUse;
//if phProcess is NULL we get process handle of this
//process.
hProcess = phProcess?*phProcess:GetCurrentProcess();
//open the processes token
if (!OpenProcessToken(hProcess,TOKEN_QUERY,&tok)) goto ert;
//get the SID of the token
ptu = (TOKEN_USER*)tubuf;
if (!GetTokenInformation(tok,(TOKEN_INFORMATION_CLASS)1,ptu,300,&nlen)) goto ert;
//get the account/domain name of the SID
dlen = 300;
nlen = 300;
if (!LookupAccountSidA(0, ptu->User.Sid, name, &nlen, dom, &dlen, (PSID_NAME_USE)&iUse)) goto ert;
//copy info to our static buffer
if (dlen && bIncDomain) {
strcpy(sname,dom);
strcat(sname,"");
strcat(sname,name);
} else {
strcpy(sname,name);
}
//set our return variable
pret = sname;
ert:
if (tok) CloseHandle(tok);
return pret;
}
int main(){
enableDebugPrivileges();
DWORD dwPID=3436;
HANDLE hProcess_i = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPID);
printf("%s",GetProcessUsername(&hProcess_i,0));
}
它的系統和curr工作良好。用戶進程,但不是網絡服務和本地服務,我得到了空string.please告訴我怎樣才能得到這些進程的用戶名。 謝謝。
有沒有什麼辦法?你可以給源嗎? – YAHOOOOO 2011-01-26 03:48:56