从编译器运行和作为独立 exe 运行时,进程访问权限似乎有所不同
我正在使用 WINAPI 来编写我正在编写的程序。该程序具有另一个进程的 ProcessId,并且需要获取它的句柄(以便稍后能够终止它,并且还可以使用 WaitForSingleObject 定期检查该进程是否处于活动状态并进行响应)。当我编译我的程序时(在 Embarcadero RAD Studio 2010 C++ Builder 中),它运行良好;该程序似乎已成功获取句柄并且通常按预期工作。但是,如果我从文件夹中将其作为独立的 exe 启动,则似乎无法正确获取句柄。我通过比较进行了检查(Companion 是一个 HANDLE,Companion_PID 是一个 DWORD):
GetProcessId(Companion)
并且
Companion_PID
在前面几行中,Companion 是从以下代码中的 Companion_PID 中获取的:
Companion = OpenProcess(PROCESS_ALL_ACCESS, FALSE, Companion_PID);
“GetProcessId(Companion)”结果为 0(这是一个好迹象表明 OpenProcess 未能返回正确的句柄,
我很惊讶该代码在从编译器运行时和作为独立 exe 运行时的工作方式不同;我假设在第一种情况下安全属性。是从编译器本身继承的,但我想听听在 WINAPI 和安全属性方面更有经验的人对这种行为的更好解释。
小更新:是的,就像我想的那样,OpenProcess 会导致错误 0x5 = ERROR_ACCESS_DENIED。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自OpenProcess函数页面 在 MSDN 中:
我相信您的 IDE(您从IDE运行应用程序,而不是编译器)默认启用了
SeDebugPrivilege
。当您运行应用程序时,您的 IDE(进程)将创建一个新进程,该进程继承 IDE 的权限,包括SeDebugPrivilege
,这就是函数从 IDE 运行时成功的原因。您的应用程序应检查是否启用了
SeDebugPrivilege
,如果没有,启用它。From OpenProcess function page in MSDN:
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, includingSeDebugPrivilege
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.