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.
Thanks in advance for your help.
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".
I would recommend NOT making this change, but instead improving your error message. It's doubtful that your application actually needs to "be root"; instead it needs certain privileges which root has, but which operating systems with fine-grained security controls might be able to grant to the application without giving it full root access. Even if that's not possible now, it may be possible 6 months or 2 years from now, and users are going to be irritated if your program is refusing to run based on backwards assumptions about the permission model rather than just checking that it succeeds in performing the privileged operations it needs to.
#include <unistd.h> // getuid
#include <stdio.h> // printf
int main()
{
if (getuid()) printf("%s", "You must be root!\n");
else printf("%s", "OK, you are root.\n");
return 0;
}
What you really want to check for is if you have the right capability set (CAP_SYS_NICE
I think is the capability you need) see man pages capabilities (7)
and capget (2)
this way it won't error out if you have the ability to do what you want, but you aren't root.