- 作者
- 赵曦
- 日期
- 2025/09/25
- 版本
- 1.0
上一篇教程:基于异步 I/O 的协程设施
下一篇教程:串口通信模块
1 命名管道
相关类:
管道是一种半双工的通信方式,允许一个进程与另一个进程进行通信。命名管道(Named Pipe)是一种特殊类型的管道,它具有名称,可以在不同的进程之间进行通信。
RMVL 提供了跨平台的命名管道实现,并提供了协程支持,Windows 下基于 Windows 命名管道,Linux 下基于 Unix FIFO 实现。
1.1 同步阻塞
服务端
C++
int main() {
bool success = server.write("message");
if (!success) {
printf("Write failed\n");
return -1;
}
std::string msg = server.read();
if (msg.empty()) {
printf("Read failed\n");
return -1;
}
printf("Received: %s\n", msg.c_str());
}
Python
import rm
success = server.write("message")
if not success:
print("Write failed")
return -1
msg = server.read()
if not msg:
print("Read failed")
return -1
print(f"Received: {msg}")
客户端
C++
int main() {
std::string msg = client.read();
if (msg.empty()) {
printf("Read failed\n");
return -1;
}
printf("Received: %s\n", msg.c_str());
bool success = client.write("received: " + msg);
if (!success) {
printf("Write failed\n");
return -1;
}
}
Python
import rm
msg = client.read()
if not msg:
print("Read failed")
return -1
print(f"Received: {msg}")
success = client.write("received: " + msg)
if not success:
print("Write failed")
return -1
1.2 异步非阻塞
服务端
bool success =
co_await server.
write(
"message");
if (!success) {
printf("Write failed\n");
co_return;
}
std::string msg =
co_await server.
read();
if (msg.empty()) {
printf("Read failed\n");
co_return;
}
printf("Received: %s\n", msg.c_str());
}
int main() {
co_spawn(io_context, session, std::move(server));
return 0;
}
异步 I/O 执行上下文,负责管理 IO 事件循环和协程任务的调度
定义 async.hpp:177
AsyncReadAwaiter read()
从管道读取数据
定义 ipc.hpp:266
AsyncWriteAwaiter write(std::string_view data)
向管道写入数据
定义 ipc.hpp:280
保有 rm::async::Promise 的异步协程任务
定义 async.hpp:146
void co_spawn(IOContext &ctx, Callable &&fn, Args &&...args)
在指定的执行上下文中生成并调度一个协程任务
定义 async.hpp:265
客户端
std::string msg =
co_await client.
read();
if (msg.empty()) {
printf("Read failed\n");
co_return;
}
printf("Received: %s\n", msg.c_str());
bool success =
co_await client.
write(
"received: " + msg);
if (!success) {
printf("Write failed\n");
co_return;
}
}
int main() {
co_spawn(io_context, session, std::move(client));
return 0;
}
AsyncReadAwaiter read()
从管道读取数据
定义 ipc.hpp:302
AsyncWriteAwaiter write(std::string_view data)
向管道写入数据
定义 ipc.hpp:316
2 消息队列(仅 Linux 可用)
相关类: rm::MqServer 及 rm::MqClient
服务端
int main() {
bool success = server.send("message");
if (!success) {
printf("Send failed\n");
return -1;
}
std::string msg = server.receive();
if (msg.empty()) {
printf("Receive failed\n");
return -1;
}
printf("Received: %s\n", msg.c_str());
}
客户端
int main() {
std::string msg = client.receive();
if (msg.empty()) {
printf("Receive failed\n");
return -1;
}
printf("Received: %s\n", msg.c_str());
bool success = client.send("received: " + msg);
if (!success) {
printf("Send failed\n");
return -1;
}
}