历趣root精灵:用C语言如何获取当前Linux系统的用户名

来源:百度文库 编辑:中科新闻网 时间:2024/04/30 05:56:23
如题。
用whoami?

可以使用getuid()获取用户的ID号,然后通过getpwuid函数通过用户的uid查找用户的passwd数据来获取系统登录的用户名。

#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
int main(void)
{
struct passwd *pwd;
pwd = getpwuid(getuid());
printf("当前登陆的用户名为:%s\n", pwd->pw_name);
return 0;
}

#include <stdio.h>
#include <pwd.h>
#include <unistd.h>

int main(void)
{
struct passwd *pwd;
pwd = getpwuid(getuid());
printf("当前登陆的用户名为:%s\n", pwd->pw_name);

return 0;
}