演示兩進程通過文本文件同步通信:寫進程每 2 秒追加一數字,讀進程每 5 秒讀取最新數字。使用 fstream + Sleep 模擬,Windows 平台。
// writer.cpp
#include <fstream>
#include <iostream>
#include <windows.h>
int main() {
std::ofstream ofs("D:/w.txt", std::ios::app); // 追加模式
int num = 0;
while (true) {
ofs << ++num << std::endl;
ofs.flush(); // 確保寫入磁盤
std::cout << "Written: " << num << std::endl;
Sleep(2000);
}
ofs.close();
return 0;
}
// reader.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
int main() {
std::vector lines;
while (true) {
Sleep(5000);
std::ifstream infile("D:/w.txt");
if (!infile) { std::cerr << "Open failed\n"; return 1; }
lines.clear();
std::string line;
while (std::getline(infile, line)) lines.push_back(line);
infile.close();
if (!lines.empty()) {
std::cout << "Latest: " << lines.back() << std::endl;
}
}
return 0;
}
| 技術點 | 說明 |
|---|---|
std::ios::app | 追加模式打開,寫入自動定位文件末尾 |
ofs.flush() | 強制刷新緩衝區到磁盤,讀進程才能讀到最新數據 |
std::getline | 按行讀取,自動處理換行符 |
全路徑 D:/w.txt | 避免工作目錄不一致導致找不到文件 |
Sleep(ms) | Windows API 線程休眠,模擬時間間隔 |
寫進程控制台輸出:
Written: 1 Written: 2 Written: 3 ...
讀進程控制台輸出(每 5 秒讀一次,讀到最新行):
Latest: 2 Latest: 4 Latest: 7 ...
tellg),增量讀取LockFileEx)、命名管道、共享內存、SocketSleep/windows.h 僅 Windows。跨平台用 std::this_thread::sleep_for (C++11)CreateNamedPipe (Win) / mkfifo (Linux),內核緩衝、阻塞同步AF_UNIX / AF_LOCAL,雙向通信、標準化Boost.Interprocess::message_queue、ZeroMQ、RabbitMQ文件同步適合簡單、低頻、跨語言場景;高併發、低延遲、雙向通信請使用專用 IPC 機制。