अंतिम अद्यतन:2026-10-12
C++ inter-process communication व्यवहार¶
Inter-process communication बहुत ज़रूरी topic है, खासकर कुछ बड़े projects में इसकी छाया रहती है, उदाहरण के लिए: PostgreSQL ने copy के inter-process communication के लिए pipes उपयोग किए, तो इस section में भी इसी theme पर, C++ से pipes के ज़रिए processes के बीच communication का demo बनाएँगे, इस section में पिछले कुछ sections की सामग्री मिलाकर एक काफी पूर्ण व्यावहारिक उदाहरण दिया जाएगा:
- mutex
- condition_variable
- thread
नोट: इस section का पूरा code 星球 में रखा जाएगा।
सबसे पहले pipes का एक बहुत सरल उपयोग:
- एक pipe बनाएँ
यह creating a pipe, forking, and invoking the shell करता है।
- Pipe बंद करें
आगे हमें बस उसमें लिखना और पढ़ना है, सिद्धांत भी बहुत सरल है, उदाहरण के लिए:
इस समय data ऊपर बनाए गए pipe में लिख दिया जाएगा।
// size_t fwrite( const void* buffer, size_t size, size_t count, FILE* stream );
size_t written = fwrite(data.c_str(), sizeof(char), data.size(), pipe);
अगर pipe से पढ़ना हो, तो हम fread या fgets उपयोग कर सकते हैं, fgets newline मिलने या buffer size तक पहुंचने पर रुक जाता है, जबकि fread जितना हो सके data पढ़ता है, जब तक निर्दिष्ट bytes की संख्या पूरी न हो जाए या file का अंत न आ जाए। इसी तरह, ऊपर का fwrite बदलकर fputs भी किया जा सकता है।
अब pipe का मूल उपयोग समझ आ गया, एक पूरा demo कैसे लिखें?
बहुत सरल है, हमें बस दो threads बनाने हैं, एक पढ़ने वाला, एक लिखने वाला, फिर writer thread pipe में data लिखे, और reader thread pipe से पढ़े।
उदाहरण के लिए:
std::thread writer_thread(write_to_pipe);
std::thread reader_thread(read_from_pipe);
writer_thread.join();
reader_thread.join();
Writer thread को करना बस इतना है कि fwrite call करके data डाल दे
ProcessWriter writer("cat > /tmp/pipe");
// 写入数据
std::string message = "Hello pipe!\n";
if (!writer.write(message)) {
std::cerr << "Failed to write data to pipe" << std::endl;
}
इसी तरह, reader thread data लेता है:
ProcessReader reader("/tmp/pipe");
// 读取数据
std::string message;
while (reader.read(message)) {
// do something
}
अंतिम परिणाम यह होगा:
संबंधित विषय¶
- खुद C++ FnOnce लिखना | C++那些事
- C++ gRPC छोटा project | C++那些事
- C++ short URL service Demo | C++那些事
- C++17 और SQLite से directory का size निकालना | C++那些事
- Google Benchmark performance testing | C++那些事
- C++20 coroutine HTTP server | C++那些事
- Protobuf ZeroCopy serialization | C++那些事
- pybind11 से Python तेज़ करना | C++那些事
- C++ stack calculator design | C++那些事