gpt4 book ai didi

c++ - 使用 fstream 向所有用户发送消息

转载 作者:行者123 更新时间:2023-11-28 00:20:33 26 4
gpt4 key购买 nike

我正在研究如何重新创建类似 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com