我正在研究如何重新创建类似 linux wall
命令的东西。
类似于echo "Hello world"|墙
这会向所有用户的 shell 发送一条消息。
在目录/dev/pts/
中有几个用于写入用户shell 的管道。所以做这样的事情很容易......
#include <fstream>
int main() {
std::ofstream wall("/dev/pts/2");
wall << "hello world" << std::endl;
return 0;
}
问题是 /dev/pts/*
对每个打开的 shell (pts/2, pts/3, ...) 都有一个提要,是吗一种更通用的方法,还是我必须枚举 /dev/pts/
中的所有提要才能从 C++ 代码向每个用户发送消息?
注意:不使用系统调用。
最佳答案
您必须枚举所有字段(如果您不打算使用系统调用)。可以这样做:
#include <fstream>
#include <string>
template <class File>
struct lock_helper // Simple fstream manager just for convenience
{
template<class... Us>
lock_helper(File& file, Us&&... us)
{
file.close();
file.open(std::forward<Us>(us)...);
}
};
int main()
{
std::ofstream out;
for (int i = 2; out; ++i)
{
lock_helper<std::ofstream> lock(out, std::string("/dev/pts/") + std::to_string(i));
out << "Hello, World\n";
}
}
关于c++ - 使用 fstream 向所有用户发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27680747/