I am using WINAPI for a program that I am writing. The program has the ProcessId of another process and needs to get a handle of it (to be able to terminate it later, and also to periodically check if the process is alive and responding by using WaitForSingleObject). When I compile my program (in Embarcadero RAD Studio 2010 C++ Builder), it works well; the program seems to get the handle successfully and generally works as intended. However, if I launch it from the folder as a standalone exe, it seems to fail to get the handle properly. I checked it by comparing (Companion is a HANDLE and Companion_PID is a DWORD):
GetProcessId(Companion)
and
Companion_PID
Where, a few lines earlier, Companion is taken from Companion_PID in the following code:
Companion = OpenProcess(PROCESS_ALL_ACCESS, FALSE, Companion_PID);
And the "GetProcessId(Companion)" results in 0 (which is a good sign that the OpenProcess failed to return a proper handle.
I'm pretty surprised that this code works differently when run from the compiler and as a standalone exe; I'm assuming in the first case the security attributes are inherited from the compiler itself, but I'd like to hear a possibly better explanation for this behaviour from someone more experienced in WINAPI and security attributes in particular.
Small update: yes, like I thought, OpenProcess results in error 0x5 = ERROR_ACCESS_DENIED.
From OpenProcess function page in MSDN:
To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.
I believe your IDE (you're running your application from IDE, not from compiler) has SeDebugPrivilege
enabled by default. When you run your application, your IDE (process) is creating a new process which inherits privileges from IDE, including SeDebugPrivilege
and that's the reason why function succeeds when run from IDE.
Your application should check whether it has SeDebugPrivilege
enabled, and if not, enable it.