· 在桌面环境中,在传统的进程间通信方式的基础上发展了更为方便的面向对象的通信方式
- KDE环境:DCOP
- GNOME环境:Bonobo
· DBUS:freedesktop开源项目的Linux IPC通信机制,KDE和GNOME环境都能支持
· Qt Embedded中定义了一种自己的轻量级的进程间通信机制QCOP
QCOP:
· QCOP利用QcopChannel类来实现.
· QcopChannel从Qobject类继承而来
- 提供了静态函数send()来发送需要传递的消息和数据
- 静态函数isRegistered()来查询某个Channel是否已经被注册
- 当从channel中接收消息和数据时,我们需要构造一个QcopChannel的子类并重写receive()函数,或者提供一个槽并利用connect()函数将receive()信号连接起来
·利用QCOP可以方便的结合qt本身的信号和槽的机制,使用非常方便
·但对于非QT程序与Qt程序的通信,则只能使用其他IPC方式
QCOP示例:
在一个进程中发送消息和数据:
QbyteArray data; QdataStream out(&data,QIODevice::WriteOnly); out<<celNum; QcopChannel::send(“/System/Temperature”,”ConvertCelTOFah(int)”,data); |
在另一个进程中接收消息和数据:
QcopChannel *channel=new QcopChannel(“/System/Temperature”,this); connect(channel,SIGNAL(received(const Qstring &, constQbyteArray&)), this,SLOT(handleMsg(const Qstring&,const QbyteArray&))); |
下面是一个示例:
//CopServ.h 作为服务端运行 –qws #ifndef CONVERSION_SCREEN_H #define CONVERSION_SCREEN_H #include <QWidget> class CopServ : public QWidget { Q_OBJECT
public: CopServ(); ~CopServ() {}; private slots: void launchFah(); void launchCel();
private: void createScreen(); void launchApp(const char* path); }; #endif //CONVERSION_SCREEN_H //CopServ.cpp程序主体 #include <QPushButton> #include <QSlider> #include <QLabel> #include <QDial> #include <QLCDNumber> #include <QVBoxLayout> #include <QHBoxLayout> #include <QGridLayout> #include <QSettings> #include <QApplication> #include <QCoreApplication> #include <unistd.h> #include <sys/types.h> #include "CopServ.h" CopServ::CopServ() : QWidget() { createScreen(); } void CopServ::createScreen() { QPushButton* celBtn = new QPushButton("Cel"); QPushButton* fahBtn = new QPushButton("Fah"); QPushButton* quitBtn = new QPushButton("Quit"); QGridLayout *mainLayout = new QGridLayout; mainLayout->addWidget(celBtn, 0, 0); mainLayout->addWidget(fahBtn, 0, 1); mainLayout->addWidget(quitBtn, 1, 0); setLayout(mainLayout); connect(celBtn, SIGNAL(clicked()), this, SLOT(launchCel())); connect(fahBtn, SIGNAL(clicked()), this, SLOT(launchFah())); connect(quitBtn, SIGNAL(clicked()), qApp, SLOT(quit())); setGeometry(0, 50, 240, 320); setWindowTitle("Server Window"); } void CopServ::launchApp(const char* path) //启动子程序 { if (path == NULL) { qDebug("Launch path is NULL!\n"); }
pid_t pid = fork(); //创建子进程 if (pid == 0) { qDebug("new process forked. PID is:%d\n", getpid()); int result = execl(path, path, 0); if (result < 0) { qDebug("failed to launch application!\n"); } _exit(-1); } } void CopServ::launchCel() { launchApp("./cel/cel"); } void CopServ::launchFah() { launchApp("./fah/fah"); } //main.cpp #include <QApplication> #include "CopServ.h" int main(int argc, char *argv[]) { QApplication app(argc, argv, QApplication::GuiServer); CopServ screen; // screen.setGeometry(0, 0, 240, 320); screen.show(); return app.exec(); } |