Check if Superuser is Executing Application on Linux using C++

Check if Superuser is Executing Application on Linux using C++

Linux provides a secure, multi-user environment where permissions and user privileges play a crucial role in system safety. When developing or running applications, it's often important to determine whether the program is being executed with superuser (root) privileges. This check can help ensure that certain operations are only performed when the necessary permissions are available. This tutorial demonstrates how to check if a superuser is executing an application on Linux using C++.

The code uses the geteuid function to retrieve the effective user ID (EUID) of the process. The effective user ID determines the privilege level under which the program is currently running - for example, whether it has superuser (root) rights. If this value equals zero, it indicates that the process has superuser privileges.

#include <unistd.h>
#include <iostream>

int main() {
    if (geteuid() == 0) {
        std::cout << "Running as superuser (root)" << std::endl;
    } else {
        std::cout << "Running as regular user" << std::endl;
    }

    return 0;
}

There also exists the getuid function, which retrieves the real user ID (UID) of the process - essentially identifying the user who launched the program. However, getuid alone is not always sufficient for checking superuser privileges because a setuid program might have elevated permissions through its effective user ID while keeping a non-zero real user ID. Therefore, when verifying privilege levels or determining if a program truly has administrative rights, using geteuid is the more reliable and appropriate choice.

Leave a Comment

Cancel reply

Your email address will not be published.