Last updated:2026-10-12
C++ Inter-Process Communication in Practice¶
Inter-process communication is a very important topic, especially since many large projects bear its traces — for example, PostgreSQL uses pipes for inter-process communication during copy. In this section, based on this theme, we will use C++ to build a demo of two processes communicating through a pipe. This section combines the content of the previous few sections to give a fairly complete practical example:
- mutex
- condition_variable
- thread
Note: the complete code for this section will be put in the Knowledge Planet community.
First, a very simple use of pipes:
- Create a pipe
It handles creating a pipe, forking, and invoking the shell.
- Close a pipe
Next, all we need to do is write into it and read from it. The principle is also very simple, for example:
This writes the data into the pipe created above.
// 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);
To read from the pipe, we can use fread or fgets. fgets stops when it reads a newline character or reaches the buffer size, while fread reads as much data as possible until the specified number of bytes is reached or end-of-file is encountered. Similarly, the fwrite above can be replaced with fputs.
Now that the basic usage of pipes has been covered, how do we write a complete demo?
It's simple: we just create two threads, one for reading and one for writing. The writer thread writes data into the pipe, and the reader thread reads from it.
For example:
std::thread writer_thread(write_to_pipe);
std::thread reader_thread(read_from_pipe);
writer_thread.join();
reader_thread.join();
All the writer thread needs to do is call fwrite to throw data in:
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;
}
Similarly, the reader thread takes the data:
ProcessReader reader("/tmp/pipe");
// 读取数据
std::string message;
while (reader.read(message)) {
// do something
}
The final result is:
Related Topics¶
- Hand-Writing C++ FnOnce | C++那些事
- A Small C++ gRPC Project | C++那些事
- C++ Short URL Service Demo | C++那些事
- C++17 and SQLite Folder Size Statistics | C++那些事
- Google Benchmark Performance Testing | C++那些事
- C++20 Coroutine HTTP Server | C++那些事
- Protobuf ZeroCopy Serialization | C++那些事
- Accelerating Python with pybind11 | C++那些事
- C++ Stack Calculator Design | C++那些事