本页内容

进程间通信

Qt 支持多种与同一系统或不同系统中运行的其他进程进行通信的方式。进程间通信机制基本分为三种类型:

  1. 同步原语
  2. 交换任意字节级数据
  3. 传递结构化消息

同步原语

Qt 仅提供一个用于显式进程间同步的类:QSystemSemaphore 。QSystemSemaphore 类似于QSemaphore ,但可被同一系统中的多个进程访问。它通过一个“密钥”进行全局标识,在 Qt 中由QNativeIpcKey 类表示。 此外,根据操作系统的不同,Qt 可能支持多种不同的内存共享后端;有关更多信息和限制,请参阅《本机 IPC 键》文档。

可以使用位于进程共享内存中的常规线程同步原语,例如互斥锁、等待条件和读写锁。Qt 并未提供任何支持此功能的类,但应用程序可以在某些操作系统上使用低级操作。

还可以使用其他 Qt 类来提供更高层次的锁定,例如QLockFile ,或者通过获取一个唯一的、系统范围内的资源。此类技术包括TCP 或UDP 中的端口,以及D-Bus 中众所周知的名称。

字节级数据共享

通过使用字节级数据,应用程序可以实现任意选择的通信协议。字节数据的共享可以是流式(序列化)的,也可以允许随机访问(类似于QFileDevice::isSequential() 的情况)。

对于串行通信,Qt 提供了多种不同的类,甚至完整的模块:

对于同一系统内的随机访问数据共享,Qt 提供了QSharedMemory 。有关详细信息,请参阅共享内存文档。

结构化消息传递

Qt 还提供多种技术,用于与其他进程交换结构化消息。应用程序可以在上述字节级解决方案的基础上进行扩展,例如通过使用QJsonDocument 或QXmlStreamReader /QXmlStreamWriter 通过 HTTP 分别执行 JSONRPC 或 XMLRPC,或者使用 QtCoAP 配合QCborValue 。

用于结构化消息和远程过程调用的专用 Qt 模块包括:

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.