linux c : get current user info and group info

前言

看了bash代码中有判断用户和用户组的实现,摘录一下。

实验

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

// 日志级别 - 调试
#ifndef LS_LOG

#define LS_LOG(fmt, ...) \
do { \
    syslog(LOG_INFO, "[%s : %s.%d : %s()] : " fmt, "LS_LOG", __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \
} while (0);

#endif // #ifndef LS_LOG

/*
Jun 12 20:04:24 localhost test_case: [LS_LOG : main.cpp.204 : test_user_and_group()] : login name : root
Jun 12 20:04:24 localhost test_case: [LS_LOG : main.cpp.205 : test_user_and_group()] : user id : 0
Jun 12 20:04:24 localhost test_case: [LS_LOG : main.cpp.206 : test_user_and_group()] : group id : 0
Jun 12 20:04:24 localhost test_case: [LS_LOG : main.cpp.207 : test_user_and_group()] : home dir : /root
Jun 12 20:04:24 localhost test_case: [LS_LOG : main.cpp.208 : test_user_and_group()] : login shell : /bin/bash
Jun 12 20:04:24 localhost test_case: [LS_LOG : main.cpp.216 : test_user_and_group()] : user group name : root
*/
void test_user_and_group()
{
    struct passwd *pw = NULL;
    struct group *grp = NULL;

    // get current user info and group info
    do {
        pw = (struct passwd *)getpwuid(getuid());
        if (NULL == pw) {
            // no password entry
            break;
        }

        LS_LOG("login name : %s\n", pw->pw_name);
        LS_LOG("user id : %d\n", (int)pw->pw_uid);
        LS_LOG("group id : %d\n", (int)pw->pw_gid);
        LS_LOG("home dir : %s\n", pw->pw_dir);
        LS_LOG("login shell : %s\n", pw->pw_shell);

        grp = (struct group *)getgrgid((gid_t)(pw->pw_gid));
        if (NULL == grp) {
            // not group entry
            break;
        }

        LS_LOG("user group name : %s", (const char*)grp->gr_name);
    } while (0);
}

猜你喜欢

转载自blog.csdn.net/lostspeed/article/details/80676267