QT Development (35)--QT interprocess communication

Source: Internet
Author: User
Tags mutex

QT Development (35)--qt interprocess communication

Qt is a cross-platform application framework, and its interprocess communication mechanism can of course use the inter-process communication mechanism of the platform, such as message mechanism on Windows platform, shared memory, file mapping, pipeline, socket and so on. Among them, Qt encapsulates some of the IPC mechanisms that are common to many platforms.

First, TCP/IP

is actually achieved through the network module Ipc. However, QT encapsulates it and provides two levels of APIs, including application-level Qnetworkaccessmanager, qftp, and the underlying qtcpsocket, Qtcpserver, Qsslsocket, and so on.



Second,Q shared Memory

QT provides shared memory based IPC with Qsharedmemory classes and Qsystemsemaphore classes, qsharedmemory can access shared memory areas, as well as multi-threaded and shared memory areas of processes , while The Qsystemsemaphore class is used to access system-shared resources for communication between independent processes.

1. qsharedmemory

When Qsharedmemory reads and writes memory, you can use lock () to achieve synchronization. If the synchronization is complete, you must use unlock () to unlock the shared memory area.

Qsharedmemory can use attach () to access shared memory and set the access mode for shared memory by specifying parameters. If you are using qsharedmemory::readonly mode, you can only access shared memory through read-only mode , and if you use qsharedmemory::readwrite mode, you will be able to access shared memory through read-write mode.

The qsharedmemory owns the process and provides a member function that can return a shared memory region pointer. In the shared memory area, the member function Constdata () can return the memory region pointer that the process is using through the void type. When you create a share, qsharedmemory can allocate shared memory regions in bytes, and you can also set the mode provided by the function attach () through the second parameter.

Qsharedmemory can set a fixed key for a specific shared memory. The function Setnativekey () can set the key of the shared memory object, and the Setnativekey () function uses the key of the shared memory of the slave platform to set the settings. Use the function Setkey () to set the platform-independent key. The function Setkey () creates a key that maps to the Platform local key (Native key).

Initialize Qsharedmemory, a unique identity key must be specified, and the key for the process must remain consistent. You can use Setkey to set up.

2. Qsystemsemaphore

The qsystemsemaphore can provide a signal volume for a common system. The semaphore uses a mutex, and the mutex can use only 1 locks (blocks). Therefore, the Qsemaphore class cannot use multi-threading for valid resources, whereas the Qsystemsemaphore class can be implemented in multiple processes or in multiple threads.

Unlike the Qsemaphore class, Qsystemsemaphore can access multiple processes. This means that Qsystemsemaphore is a heavyweight class. Therefore, it is recommended to use Qsemaphore when using a single thread or process. The member function acquire () is always blocked until the resource is obtained. The function release () is used to free resources, and the function can set parameters. When the parameter of the function is >1, the resource is freed.

3. qsharedmemory Programming Process

Shared in-memory data providers:

A, define qsharedmemory sharememory, and set the flag name Sharememory.setkey ();

B, separate the shared memory from the main process Sharememory.detach ();

C, Create shared Memory sharememory.create ();

D, Lock the shared memory Sharememory.lock ();

E. Copy the data to be shared in the process to the shared memory;

F, the shared memory is unlocked sharememory.unlock ();

Shared in-memory data consumer:

A, define Qsharedmemory sharememory, and set the flag name Sharememory.setkey () that is consistent with the shared Memory provider .

B, Lock the shared memory Sharememory.lock ();

C, bind the shared memory with the main process Sharememory.attach (), so that the main process can access the shared memory data;

D . Fetching data from shared memory;

E. after use, the shared memory is unlocked sharememory.unlock () andthe shared memory is separated from the process Sharememory.detach ();

4. qsharedmemory working with Instances

Shared memory data Provider code:

Widget.h file:

#ifndef widget_h#define widget_h#include <QtGui/QWidget> #include <qsharedmemory>class widget:public    qwidget{q_object public:widget (qwidget *parent = 0); ~widget ();p rivate:qsharedmemory sharememory;private slots:void writesharememory ();}; #endif//Widget_h

Widget.cpp file:

#include   "Widget.h" #include  <QBuffer> #include  <QDebug> #include  <qdatastream >widget::widget (Qwidget *parent)     : qwidget (parent) {     sharememory.setkey ("Share");     this->writesharememory ();} Widget::~widget () {    }void widget::writesharememory () {    if ( Sharememory.isattached ())     {         Sharememory.detach ();    }    qbuffer buffer;     qdatastream out (&buffer);     buffer.open (Qbuffer::readwrite);     buffer.write ("hello qt!");     int size = buffer.size ();     if (!sharememory.create (size))     {        qdebug ()  <<  Sharememory.erroRString ();        return ;    }     sharememory.lock ();     char *dest = reinterpret_cast<char  *> (Sharememory.data ());     const char *source = reinterpret_ Cast<const char *> (Buffer.data (). data ());     memcpy (Dest, source,  qmin (Size, sharememory.size ()));     sharememory.unlock ();}

Main.cpp file:

#include <QtGui/QApplication> #include "Widget.h" int main (int argc, char *argv[]) {qapplication A (argc, argv);    Widget W;    W.show (); return a.exec ();}

Shared Memory data Consumer code:

Widget.h files: #ifndef widget_h#define widget_h#include <QtGui/QWidget> #include <qsharedmemory>class widgets    : Public qwidget{q_object public:widget (qwidget *parent = 0); ~widget ();p rivate:qsharedmemory sharememory;private slots:void readsharememory ();}; #endif//Widget_h

Widget.cpp file:

#include   "Widget.h" #include  <QBuffer> #include  <QDebug> #include  <qdatastream >widget::widget (Qwidget *parent)     : qwidget (parent) {     sharememory.setkey ("Share");     this->readsharememory ();} Widget::~widget () {    }void widget::readsharememory () {    if (! Sharememory.attach ())     {        qdebug ()   <<  "Cann ' t attach sahrememory! ";    }    qbuffer buffer;     Sharememory.lock ();     buffer.setdata ((char*) Sharememory.constdata (), sharememory.size ());     buffer.open (Qbuffer::readwrite);     buffer.readall ();     sharememory.unlock ();     sharememory.detach ();     qdebug ()  << buffer.data (). data ();} 

Main.cpp file:

#include <QtGui/QApplication> #include "Widget.h" int main (int argc, char *argv[]) {qapplication A (argc, argv);    Widget W;        W.show (); return a.exec ();}
Third, D-bus

D_bus is a low-overhead, low-latency inter-process communication mechanism. QT provides the Qtdbus module ,the Qtdbus module uses the D-bus protocol to extend the signal and slot mechanism (Signal and slot) to the process level, allowing developers to signal in one process, and other processes to define slots to respond signals sent by other processes.

D-bus is an advanced inter-process communication mechanism, provided by the Freedesktop.org project and issued with a GPL license. The primary purpose of D-bus is to provide communication to the process in the Linux desktop environment while delivering the Linux desktop environment and Linux kernel events as messages to the process. The main probability of D-bus is the bus, the registered process can receive or pass the message through the bus, the process can also register and wait for the kernel event response, such as waiting for the network state to change or the computer to issue a shutdown command. Currently, D-bus has been adopted by most Linux distributions, and developers can use D-bus to achieve a variety of complex interprocess communication tasks.

D-bus is a message bus system that features all of the requirements for interprocess communication and has some special uses. D-bus is a three-tier Inter-process communication system that includes:

interface layer: The interface layer is provided by the library Libdbus, and the process is capable of using d-bus through the Libdbus library.

Bus layer: The bus layer is actually made up of Provided by the D-bus bus daemon. Run at Linux system startup, responsible for message routing and delivery between processes, including the Linux kernel and the Linux desktop environment.

Packaging Layer: Packaging layer a series of application-specific framework-based Wrapper library.

in the The Dbus in Qt is used by the Dbus packaging layer libdbus-qt.

to view Services and objects on the Dbus bus can be d-feet and qdbusviewer

To send a signal you can use dbus-send, to view the message flow on Dbus can use Dbus-monitor

Four, Qcop (Qt COmmunications Protocol)

QCOP is a communication protocol within QT that is used to communicate between different customers within the same address space or between different processes. Currently, this mechanism is only available in the embedded version of Qt.

to be implement this communication mechanism, Qt includes the Qcopchannel class inherited by the Qobject class, which provides static functions such as Send (), isregistered (), which can be used in the case of a detached object. In order to receive communication data in the channel, the user needs to construct a subclass of Qcopchannel and provide an overloaded function of the receive () function, or use the Connect () function to connect to the received signal. It is worth mentioning that in the Qt system, only the QCOP protocol mechanism and the class used to receive the message are provided, and how the message is sent does not provide the appropriate class for the user to use.

in the based on Qt's desktop system Qtopia (QPE), the corresponding send class is provided: Qcopenvelope. This class enables users to use the channel to send messages to other processes. The class is encapsulated by the process of sending QCOP messages through Qcopchannel, which allows users to easily communicate between processes by simply invoking the relevant functions in the class.

Five, qprocess

Cross-platform classes Qprocess can be used to start external programs as child processes and communicate with them. It provides an API for monitoring and controlling the status of this subprocess. In addition, Qprocess provides input/output channels for child processes that inherit from Qiodevice.

Six, Session Management

in the On the linux/x11 platform, QT provides session management support. Sessions allow events to propagate to processes, for example, when a shutdown is detected. Processes and applications can perform any necessary actions, such as saving open documents.


This article from "Life is endless, struggle not only" blog, declined reprint!

QT Development (35)--QT interprocess communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.