/* * msgQ1.c++ POSIX message queue * $ g++ -Wall msgQ1.c++ -lrt * $ sudo ./a.out w; ./a.out r */ #include using namespace std; #include #include #include #include #include #include #include #include #include #define MSGSIZE 1024 #define MAXMSG 16 int main(int ac, char *av[]){ struct mq_attr attr; int err, msgLen; mqd_t mqd; if(ac < 2){ cerr << "r/w not specified\n"; exit(1); } attr.mq_maxmsg = MAXMSG; attr.mq_msgsize = MSGSIZE; attr.mq_flags = 0; attr.mq_curmsgs = 0; if(av[1][0] == 'w'){ char buff[MSGSIZE]; int prio=0; mqd = mq_open("/myMq", O_WRONLY | O_CREAT, 0777, &attr); if(mqd == -1){ cerr << "mq_open() problem: " << errno << endl; exit(1); } cout << "Enter message (terminate with Ctrl-D): "; while(1) { cin.getline(buff, MSGSIZE); err = mq_send(mqd, buff, strlen(buff), prio++); if(err == -1){ cerr << "mq_send() fails\n"; exit(1); } if(cin.eof()) break; } } if(av[1][0] == 'r'){ char buff[MSGSIZE]; mqd = mq_open("/myMq", O_RDONLY | O_CREAT, 0777, &attr); if(mqd == -1){ cerr << "mq_open() problem: " << errno << endl; exit(1); } cout << "Reader reads message: \n"; while((msgLen = mq_receive(mqd, buff, MSGSIZE, NULL)) != -1){ buff[msgLen]='\0'; if(msgLen != 0) cout << "Received message: " << buff << endl; } } mq_close(mqd); return 0; }