2014-12-28 33 views
0

我正在研究如何重新創建類似於linux wall命令的內容。使用fstream向所有用戶發送消息

echo "Hello world" | wall

這將消息發送到所有用戶的炮彈。

在目錄/dev/pts/是用於寫入用戶shell的多個管道。所以這是很容易做到像...

#include <fstream> 

int main() { 
    std::ofstream wall("/dev/pts/2"); 
    wall << "hello world" << std::endl; 
    return 0; 
} 

的問題是,/dev/pts/*對每個開殼飼料(PTS/2,PTS/3,...),有沒有更一般的方式來做到這一點,或者我將不得不枚舉/dev/pts/中的所有提要從C++代碼向每個用戶發送消息?

注意:不使用系統調用。

回答

3

你將不得不枚舉所有的字段(如果你不打算使用系統調用)。這可以這樣做:

#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"; 
    } 
} 
+0

哇,這是一個非常優雅的解決方案。我覺得更簡單了。 – MatUtter

相關問題