目标C和操作系统用户类型 [英] Objective C and OS user type

查看:154
本文介绍了目标C和操作系统用户类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过目标C获取当前登录的用户类型(root,admin或normal)?

Is there any way to get currently logged in user type (root, admin or normal) through objective C?

我知道 NSFullUserName

I know about NSFullUserName() which gives user name, but how to retrieve user type?

感谢。

推荐答案

您可以使用 getpwnam getpwuid 检索用户组使用 getgrgid 从gid获取组名称。

You can retrieve the user group using getpwnam or getpwuid then use getgrgid to get the group name from the gid.

这些是标准库中的C函数。

These are C functions in the standard library.

- 编辑:以下是一个简短的,编码不良的C示例---

-- Here is a short, poorly coded C example ---

例如,在终端中的mac os应该使用make(如果你命名文件 getpwnam_example.c 你可以做 $ make getpwnam_example 在与c文件相同的目录中)。

Here is a small example, on mac os in the terminal it should build using make (if you name the file getpwnam_example.c you can do $ make getpwnam_example in the same directory as the c file).

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <strings.h>
#include <pwd.h>
#include <grp.h>

int main(int argc, char **argv) {

    uid_t current_user_id = getuid();
    printf("My Current UID is %d\n", current_user_id);

    struct passwd *pwentry = getpwuid(current_user_id);
    printf("My Current Name is %s\n", pwentry->pw_gecos);
    printf("My Current Group ID is %d\n", pwentry->pw_gid);

    struct group *grentry = getgrgid(getgid());
    printf("My Current Group Name is %s\n", grentry->gr_name);

    printf("Am I an admin? ");
    struct group *admin_group = getgrnam("admin");
    while(*admin_group->gr_mem != NULL) {
        if (strcmp(pwentry->pw_name, *admin_group->gr_mem) == 0) {
            printf("yes!\n");
        }
        admin_group->gr_mem++;
    }

    return 0;
}

这篇关于目标C和操作系统用户类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆