我正在开发一个C应用程序,其中我需要当前登录用户的名称 . 我尝试使用 getlogin()
和 getlogin_r()
但没有成功 (tested on multiple systems with Ubuntu 16.04 LTS) . 应用程序将以root身份运行,因此我无法使用环境变量 .
getlogin()
和 getlogin_r()
在其他Ubuntu 17.04 / 17.10 / 18.04(测试版)上工作正常,所以我不会在16.04工作 .
这是我用来测试的代码片段:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
int main(int argc, char *argv[])
{
char user[512] = {0};
int ret = getlogin_r(user, 512);
if ( ret != 0){
fprintf(stderr, "Unable to get User name. Return: %d\n", ret);
}
else{
fprintf(stdout, "Username: %s\n", user);
}
char *lgn;
struct passwd *pw;
if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL)
{
fprintf(stderr, "Get of user information failed.\n");
}
struct passwd *pwd = getpwuid(getuid());
if (pwd){
fprintf(stdout, "Success! Username: %s\n", pwd->pw_name);
}else
fprintf(stderr, "Failed");
return 0;
}
这是我以root身份执行代码时生成的输出:
Unable to get User name. Return : 2
Get of user information failed.
Success! Username: root
getpwuid
返回运行该进程的用户的详细信息,因此没有用处 .
我现在有点困惑,非常感谢任何帮助 .
使用 strerror()
输出
getlogin_r() : No such process
getlogin() : No such file or directory
Success! Username: root