Got error code(5) access denied when use Terminate

2020-07-19 23:41发布

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".

2条回答
Melony?
2楼-- · 2020-07-20 00:14

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

查看更多
趁早两清
3楼-- · 2020-07-20 00:36

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.

查看更多
登录 后发表回答