How can my C / C ++ application determine if the user will execute root?

I am writing an application that requires root user rights. If executed by a non-user, it exits and ends with a perror message, for example:

    pthread_getschedparam: Operation not permitted

I would like to make the application more user friendly. As part of an early initialization, I would like it to check if it is root or not. And if not root, a message will appear in it stating that it can only be run as root, and then complete.

Thanks in advance for your help.

+5
source share
4 answers

getuidor geteuidwould be an obvious choice.

getuid .

e geteuid effective. .

, sudo root (), , - ( wheel ..)

, :

#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";
}

, getuid() geteuid() , " ". sudo./a.out, getuid() , geteuid() root wheel, " - ".

+11

, . , "root"; , root, , . , , 6 2 , , , , , .

+12
#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;
}
+7
source

What you really want to check is if you have the right set of features ( CAP_SYS_NICEI think this is a necessary feature) see the man pages capabilities (7)and capget (2)in such a way that it will not log out if you are able to do something what you want but you are not root.

+5
source

All Articles