I am writing an application that requires root user privileges to execute. If executed by a non root user, it exits and terminates with a perror message such as:
<
getuid or geteuid would be the obvious choices.
getuid checks the credentials of the actual user.
The added e in geteuid stands for effective. It checks the effective credentials.
Just for example, if you use sudo to run a program as root (superuser), your actual credentials are still your own account, but your effective credentials are those of the root account (or a member of the wheel group, etc.)
For example, consider code like this:
#include
#include
int main() {
auto me = getuid();
auto myprivs = geteuid();
if (me == myprivs)
std::cout << "Running as self\n";
else
std::cout << "Running as somebody else\n";
}
If you run this normally, getuid() and geteuid() will return the same value, so it'll say "running as self". If you do sudo ./a.out instead, getuid() will still return your user ID, but geteuid() will return the credentials for root or wheel, so it'll say "Running as somebody else".