服务端:
#include <fcntl.h> /* For O_* constants */ #include <sys/stat.h> /* For mode constants */ #include <mqueue.h> #include <unistd.h> #include <syslog.h> #define MQNAME "/fifo1" mqd_t m_mq;//message queue object bool bExitThread = false;//exit thread condition pthread_t g_thread;//thread object void* Process(void* args) { while(true){ if(bExitThread){ break; } char cData[1024] = {"123"}; int nSend = mq_send(m_mq, cData, strlen(cData), 0);//nonblock if(errno == EAGAIN){ syslog(LOG_DEBUG, "EAGAIN"); } if(errno == EBADF){ syslog(LOG_DEBUG, "EBADF"); } if(errno == EINTR){ syslog(LOG_DEBUG, "EINTR"); } if(errno == EINVAL){ syslog(LOG_DEBUG, "EINVAL"); } if(errno == EMSGSIZE){ syslog(LOG_DEBUG, "EMSGSIZE"); } if(errno == ETIMEDOUT){ syslog(LOG_DEBUG, "ETIMEDOUT"); } usleep(1000 * 1000);//sleep one second } } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_mq = mq_open(MQNAME, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH, NULL); mq_attr m_attr; mq_getattr(m_mq, &m_attr);// get attribute from mq m_attr.mq_flags |= O_NONBLOCK; mq_setattr(m_mq, &m_attr, NULL);//set nonblock pthread_create(&g_thread, NULL, Process, this);//start thread } MainWindow::~MainWindow() { bExitThread = true;//break-thread signal pthread_join(g_thread, NULL); //wait thread exit mq_close(m_mq); //close mq object mq_unlink(MQNAME);//delete mq from kernel delete ui; }客户端:
#include <fcntl.h> /* For O_* constants */ #include <sys/stat.h> /* For mode constants */ #include <mqueue.h> #include <unistd.h> #include <syslog.h> #define MQNAME "/fifo1" mqd_t m_mq; bool bExitThread = false; pthread_t g_thread; void* Process(void* args) { while(true){ if(bExitThread){ break; } char cData[8192] = {0}; ssize_t nRecv = mq_receive(m_mq, cData, 8192, 0); if(errno == EAGAIN){ syslog(LOG_DEBUG, "EAGAIN"); } if(errno == EBADF){ syslog(LOG_DEBUG, "EBADF"); } if(errno == EINTR){ syslog(LOG_DEBUG, "EINTR"); } if(errno == EINVAL){ syslog(LOG_DEBUG, "EINVAL"); } if(errno == EMSGSIZE){ syslog(LOG_DEBUG, "EMSGSIZE"); } if(errno == ETIMEDOUT){ syslog(LOG_DEBUG, "ETIMEDOUT"); } usleep(1000 * 1000); } } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_mq = mq_open(MQNAME, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, NULL); pthread_create(&g_thread, NULL, Process, this); } MainWindow::~MainWindow() { bExitThread = true; pthread_join(g_thread, NULL); mq_close(m_mq); mq_unlink(MQNAME); delete ui; }