Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got error code(5) access denied when use TerminateProcess to terminate the "mstsc.exe" process

I use the CreateProcess() function to launch the rdp client app using "mstsc.exe". After that, I want to terminate it so I use TerminateProcess() function, but it fails with error code of 5. If I replace the "mstsc.exe" with "notepad.exe", the terminate function works. The code are as follows:

TCHAR szCommandLine[] = TEXT("mstsc.exe");
STARTUPINFO si = {sizeof(si)};
PROCESS_INFORMATION pi;
BOOL bResult = CreateProcess(NULL, szCommandLine, NULL, NULL,
    FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
::Sleep(3000);
if (TerminateProcess(pi.hProcess, 0) == 0) {
printf("failed: %d", GetLastError());
}

Can anyone help explain it and solve it? What I observed is that the pid of the pi returned is different from the id of the process "mstsc.exe" observed in taksmanager or "Process Explorer".

like image 792
Henry Avatar asked Aug 23 '12 15:08

Henry


2 Answers

Is your host process 32-bit and you are running on 64-bit windows?

If so, you are invoking the 32-bit mstsc and it is spawning a 64-bit version, hence the different PID. Check out this thread

like image 135
Rob Walker Avatar answered Oct 13 '22 22:10

Rob Walker


You must gain the privilege before terminating another process.

Try this:

void UpdatePrivilege(void)
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tp;
    LUID luid;

    if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,&hToken))
    {
       LookupPrivilegeValue(NULL,SE_DEBUG_NAME, &luid);

       tp.PrivilegeCount = 1;
       tp.Privileges[0].Luid = luid;
       tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 

       AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
    }
}

Call this function before calling TerminateProcess.

like image 44
Rango Avatar answered Oct 13 '22 23:10

Rango