getlogin_r() 和 getlogin() 只适用于 tty

getlogin_r() and getlogin() do only work on tty

本文关键字:getlogin 适用于 tty      更新时间:2023-10-16

我写了一个测试程序来检查getlogin_r()和getlogin()是否有效,因为我之前遇到过问题并且无法修复它。在TTY中,它工作正常,两个函数都返回我的用户名,但在LXDE终端中执行,发生以下错误:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid

我正在运行此代码,并安装了Raspbian的Raspberry Pi 2 B。这是我的代码:

#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
    char user[64];
    getlogin_r(user,sizeof(user)-1);
    string getlogin_r_str(user);
    string getlogin_str(getlogin());
    cout << "getlogin_r(): " << getlogin_r_str << endl << "getlogin(): " << getlogin_str << endl;
    return 0;
}

这很可能是因为 LXDE 终端没有更新记录所有登录用户的 utmp 信息,getlogin根据该信息确定用户名。

您应该接受getlogin可以返回空指针并优雅地处理它,例如,如果getlogin失败,则使用 getpwuid

#include <pwd.h>
#include <unistd.h>
#include <string>
std::string get_username() {
    struct passwd *pwd = getpwuid(getuid());
    if (pwd)
        return pwd->pw_name;
    else
        return "(?)";
}