给我介绍几种qt进程间通信的方式的代码
时间: 2023-07-16 08:16:36 浏览: 136
进程间通信代码
4星 · 用户满意度95%
1. 信号与槽机制
发送者代码:
```c++
// 发送者
void Sender::sendData() {
QString data = "Hello Receiver!";
emit sendData(data);
}
```
接收者代码:
```c++
// 接收者
Receiver::Receiver() {
connect(this, &Receiver::sendData, this, &Receiver::receiveData);
}
void Receiver::receiveData(QString data) {
qDebug() << "Received data: " << data;
}
```
2. 共享内存
创建共享内存:
```c++
// 创建共享内存
QSharedMemory sharedMemory("MySharedMemory");
if (!sharedMemory.create(sizeof(int))) {
qDebug() << "Unable to create shared memory segment";
return;
}
```
写入共享内存:
```c++
// 写入共享内存
int* sharedData = static_cast<int*>(sharedMemory.data());
*sharedData = 42;
```
读取共享内存:
```c++
// 读取共享内存
int* sharedData = static_cast<int*>(sharedMemory.data());
int data = *sharedData;
qDebug() << "Data from shared memory: " << data;
```
3. 本地套接字
服务端代码:
```c++
// 服务端
QLocalServer* server = new QLocalServer();
server->listen("MyLocalSocket");
connect(server, &QLocalServer::newConnection, [=]() {
QLocalSocket* socket = server->nextPendingConnection();
connect(socket, &QLocalSocket::readyRead, [=]() {
qDebug() << "Received data: " << socket->readAll();
});
});
```
客户端代码:
```c++
// 客户端
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer("MyLocalSocket");
if (socket->waitForConnected()) {
socket->write("Hello server!");
}
```
4. D-Bus
服务端代码:
```c++
// 服务端
QDBusConnection connection = QDBusConnection::sessionBus();
connection.registerObject("/com/MyApp", this);
connection.registerService("com.MyApp");
// 实现接口方法
QString MyApp::echo(const QString& message) {
return message;
}
```
客户端代码:
```c++
// 客户端
QDBusConnection connection = QDBusConnection::sessionBus();
QDBusInterface interface("com.MyApp", "/com/MyApp", "com.MyApp");
// 调用接口方法
QDBusReply<QString> reply = interface.call("echo", "Hello server!");
if (reply.isValid()) {
qDebug() << "Received reply: " << reply.value();
}
```
阅读全文