How can my C/C++ application determine if the root

2019-02-13 22:39发布

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.

标签: c++ c linux root
4条回答
何必那么认真
2楼-- · 2019-02-13 22:50

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-13 22:56
#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;
}
查看更多
闹够了就滚
4楼-- · 2019-02-13 23:03

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.

查看更多
看我几分像从前
5楼-- · 2019-02-13 23:16

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".

查看更多
登录 后发表回答