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:
pthread_getschedparam: Operation not permitted
I would like to make the application more user friendly. As part of its early initialization I would like it to check if it is being executed by root or not. And if not root, it would present a message indicating that it can only be run by root, and then terminate.
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 <unistd.h>
#include <iostream>
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".