How can I get the username of the process owner (the user who is executing my program) in C++?
IDK, but in a batch file you can use %username%. if its windows, and you only need to echo it, then
system("echo %username%");i believe
This is specific to the operating system. On Windows, use GetUserName. On unix, use getuid.
Windows
Example:
char user_name[UNLEN+1];
DWORD user_name_size = sizeof(user_name);
if (GetUserName(user_name, &user_name_size))
cout << "Your user name is: " << user_name << endl;
else
/* Handle error */
Linux
Look at getpwuid:
The getpwuid() function shall search the user database for an entry with a matching uid.
The getpwuid() function shall return a pointer to a struct passwd
The struct passwd
will contain char *pw_name
.
Use getuid
to get the user id.
It is not a C++ related question. You can find information (not 100% sure) in the environment variables when using UNIX like systems. You can also use the 'id' program on these systems.
In general, the fastest way is to make a platform-dependent kernel / API call.
On windows under cmd.exe the USERNAME environment variable holds the username (which is also informational not factual). Search in WINAPI documentation for precise.
On windows, a thread can be impersonated, a process can not. To get the process owner you should call GetTokenInformation with the TokenUser infoclass on your process token, this will give you a SID, this SID can be converted to a username with LookupAccountSid. If you don't care about thread vs process, GetUserName() is fine.