getlogin_r() 和 getlogin() 只适用于 tty
getlogin_r() and getlogin() do only work on tty
我写了一个测试程序来检查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 "(?)";
}
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 适用于 WebView2 旧版本的示例应用程序
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 Linux 的 c++ 上的代理脚本
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 有没有适用于Windows.lib文件的GNU二进制文件描述符(BFD)
- 模板函数仅适用于VS
- 如何在cmake中包含适用于g++或viceversa的库
- 适用于win32、linux、mac的POSIX C包装器
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- getlogin_r() 和 getlogin() 只适用于 tty