How can my C/C++ application determine if the root user is executing the command?

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 are not root!\n");
    else printf("%s", "OK, you are root.\n");
    return 0;
}

Tags:

Linux

C++

C

Root