In the Linux system, every user is recognized by a unique identifier referred to as a user ID or UID. This identifier plays a crucial role in determining the system resources accessible to each user. This tutorial explains how to get user ID (UID) on Linux using C++.
Current user
The provided code snippet can be used to retrieve the UID of the current user in a Linux environment by utilizing the getuid
function:
#include <iostream>
#include <unistd.h>
int main()
{
unsigned int uid = getuid();
std::cout << uid << std::endl;
return 0;
}
Other user
The following code can be used to get the UID of a specified user (www-data
in this case) in a Linux environment. The getpwnam
function is utilized to retrieve the user account information by username. This function returns the passwd
structure from which UID can be extracted.
#include <iostream>
#include <pwd.h>
int main()
{
const char *username = "www-data";
passwd *pwd = getpwnam(username);
unsigned int uid = pwd->pw_uid;
std::cout << uid << std::endl;
return 0;
}
Leave a Comment
Cancel reply