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

标签 c++ shell debian fstream

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

相关文章:

C++:无法将 vector 传递给构造函数

shell - 如何将命令参数中的引号转义为 sh -c?

java - 出现 fatal error : jni. h : No such file or directory #include <jni. h>

c++ - C++ 中的 const 对象

linux - Grep 查找行号后的下一个空行

shell - 使用awk提取最大值和最小值

cassandra - 未满足依赖项的 cassandra 安装失败

python - 如何配置 uwsgi 以使用特定版本的 python?

linux - VMware server 1.0.7 模块与内核 2.6.26 不兼容——已打补丁,提交到哪里?

c++ - 具有模板化类成员函数的多线程