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.
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.
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 pagescapabilities (7)
andcapget (2)
this way it won't error out if you have the ability to do what you want, but you aren't root.getuid
orgeteuid
would be the obvious choices.getuid
checks the credentials of the actual user.The added
e
ingeteuid
stands foreffective
. 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:
If you run this normally,
getuid()
andgeteuid()
will return the same value, so it'll say "running as self". If you dosudo ./a.out
instead,getuid()
will still return your user ID, butgeteuid()
will return the credentials for root or wheel, so it'll say "Running as somebody else".