简体   繁体   中英

AttachConsole Error 5: Access is denied

I'm working with a C++ Console Application in Visual Studio 2013, working on Windows.

First I detached the console using FreeConsole , it works; then, called AllocConsole as FreeConsole then AttachConsole not working suggested, returns true meaning success; last, I tried to attach it back using AttachConsole , but nothing happened --

#include <psapi.h>

DWORD winpid = GetCurrentProcessId(); // get pid
std::cout << winpid; // it works    
FreeConsole(); // console lost
bool succeed = AllocConsole(); //succeeded.
succeed = AttachConsole(winpid); // return false: failed.
if (!succeed)
    LastError = GetLastError(); // Error Code 5

System Error Code 5 means :

ERROR_ACCESS_DENIED
5 (0x5)
Access is denied.

How shall I attach the console properly?

Remove the AllocConsole call before AttachConsole.

From the documentation : A process can be attached to at most one console. If the calling process is already attached to a console, the error code returned is ERROR_ACCESS_DENIED (5).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM