读书人

linux获取登录当前系统的用户名和UID解

发布时间: 2012-04-18 15:01:59 作者: rapoo

linux获取登录当前系统的用户名和UID
请问一下linux中如何用函数获取登录当前系统的UID和用户名啊,就是开机时输入的那个。 我的系统是Fedora 14.

[解决办法]
那就先getlogin, 然后从用户名获取uid, 用getpwnam

NAME
getpwnam, getpwnam_r, getpwuid, getpwuid_r - get password file entry
SYNOPSIS
#include <sys/types.h>
#include <pwd.h>

struct passwd *getpwnam(const char *name);

DESCRIPTION
The getpwnam() function returns a pointer to a structure containing the broken out fields of a line from /etc/passwd for the entry that matches the user name name.
The getpwuid() function returns a pointer to a structure containing the broken out fields of a line from /etc/passwd for the entry that matches the user uid uid.

The passwd structure is defined in <pwd.h> as follows:


struct passwd {
char *pw_name; /* user name */
char *pw_passwd; /* user password */
uid_t pw_uid; /* user id */
gid_t pw_gid; /* group id */
char *pw_gecos; /* real name */
char *pw_dir; /* home directory */
char *pw_shell; /* shell program */
};


[解决办法]
getpwent()直接获取passwd结构体,其中的pw_name,pw_uid

读书人网 >UNIXLINUX

热点推荐