(1)获取linux系统的用户名:
通过 struct
passwd *getpwuid(uid_t uid)函数; 该函数返回passwd结构体,此结构体中包含用户名字段
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;
/*user real name */
char
*pw_dir;
/*home directory */
char
*pw_shell;
/*shell program */
};
(2)获取windows系统的用户名:
通过GetUserName( buffer , &len ) 函数
(3)完整的实例(跨平台):
- #include <iostream>
- #include <string>
- #ifdef linux
- #include <unistd.h>
- #include <pwd.h>
- #endif
- #ifdef _WIN32
- #include<Windows.h>
- #endif
- std::string getUserName()
- {
- #if defined linux //linux system
- uid_t userid;
- struct passwd* pwd;
- userid=getuid();
- pwd=getpwuid(userid);
- return pwd->pw_name;
- #elif defined _WIN32 //windows system
- const int MAX_LEN = 100;
- char szBuffer[MAX_LEN];
- DWORD len = MAX_LEN;
- if( GetUserName(szBuffer, &len) ) //用户名保存在szBuffer中,len是用户名的长度
- return szBuffer;
- #else //outher system
- return "";
- #endif
- }
- int main()
- {
- std::string ss = getUserName();
- std::cout << ss << std::endl;
- return 0;
- }
(5)linux下的四个简单函数介绍:getpid, getppid, getuid, getgid
#include <stdio.h>
int main()
{
printf("pid:%d, ppid:%d, uid:%d, gid:%d\n", getpid(), getppid(), getuid(), getgid());
return 0;
}
结果为:
[taoge@localhost learn_c]$ echo $$
2774
[taoge@localhost learn_c]$ id
uid=501(taoge) gid=502(taoge) groups=502(taoge),501(embed)
[taoge@localhost learn_c]$ ./a.out
pid:2898, ppid:2774, uid:501, gid:502
2774
[taoge@localhost learn_c]$ id
uid=501(taoge) gid=502(taoge) groups=502(taoge),501(embed)
[taoge@localhost learn_c]$ ./a.out
pid:2898, ppid:2774, uid:501, gid:502
[taoge@localhost learn_c]$ su root
Password:
[root@localhost learn_c]# echo &&
>
[root@localhost learn_c]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
[root@localhost learn_c]# ./a.out
pid:2922, ppid:2905, uid:0, gid:0
Password:
[root@localhost learn_c]# echo &&
>
[root@localhost learn_c]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
[root@localhost learn_c]# ./a.out
pid:2922, ppid:2905, uid:0, gid:0
[root@localhost learn_c]# su taoge
[taoge@localhost learn_c]$ echo $$
2928
[taoge@localhost learn_c]$ id
uid=501(taoge) gid=502(taoge) groups=502(taoge),501(embed)
[taoge@localhost learn_c]$ ./a.out
pid:2946, ppid:2928, uid:501, gid:502
[taoge@localhost learn_c]$
[taoge@localhost learn_c]$ echo $$
2928
[taoge@localhost learn_c]$ id
uid=501(taoge) gid=502(taoge) groups=502(taoge),501(embed)
[taoge@localhost learn_c]$ ./a.out
pid:2946, ppid:2928, uid:501, gid:502
[taoge@localhost learn_c]$
#include <unistd.h>
#include <pwd.h>
void GetUserAndPid()
{
uid_t userid;
struct passwd* pwd;
userid=getuid();
pwd=getpwuid(userid);
FILE *fp = fopen("/home/stamp_temp/ao.log", "ab+");
fprintf(fp, "user:%s, pid:%d, ppid:%d, uid:%d, gid:%d\n", pwd->pw_name, getpid(), getppid(), getuid(), getgid());
fclose(fp);
}