ANP - 4. IPC-message Queue
ANP - 4. IPC-message Queue
1
7/21/2017
2
7/21/2017
CreateMessageQueue.c CreateMessageQueue.c
#include <mqueue.h> // First we need to set up the attribute structure
#include <stdlib.h> attr.mq_maxmsg = 5;
#include <stdio.h> attr.mq_msgsize = MSG_SIZE;
attr.mq_flags = 0;
#include <errno.h>
attr.mq_curmsgs=0;
#define MSG_SIZE 4096
// Open a queue with the attribute structure
int main (int argc,char* *args) { mqdes = mq_open (args[1], O_RDWR | O_CREAT, 0664, &attr);
struct mq_attr attr; if(mqdes==-1){
mqd_t mqdes; printf("error: %s (%d)\n",strerror(errno),errno);
if(argc!=2){ return 1;
fprintf(stderr,"Usage: %s MessageQueueName\n",args[0]); }
fprintf(stderr,"For Example #%s /myMQ\n",args[0]); printf("Message Queue with the name %s has been successfully
created.\n",args[1]);
exit(0);
return 0;
}
mq_close (mqdes); //why
}
3
7/21/2017
SendMessage.c SendMessage.c
#include <mqueue.h> if(argc!=3){
#include <stdlib.h> fprintf(stderr,"Usage: %s <Message-Queue Name> <Message
#include <stdio.h> Priority>\n",args[0]);
#include <errno.h> fprintf(stderr,"For Example #%s /myMQ 1\n",args[0]);
#define MSG_SIZE 4096 exit(0);
int main (int argc,char* *args) { }
struct mq_attr attr;
mqd_t mqdes; /* Open a queue with the attribute structure */
int priority; priority=atoi(args[2]);
char message[4096]; mqdes = mq_open (args[1], O_WRONLY);
if(mqdes==-1){
printf("error: %s (%d)\n",strerror(errno),errno);
return 1;
}
SendMessage.c ReceiveMessage.c
/* Take message from user through keyboard */ #include <mqueue.h>
printf("Type your message below...Press Enter to input\n"); #include <stdlib.h>
fgets(message,4096,stdin); #include <stdio.h>
/* Send the message */ #include <errno.h>
mq_send(mqdes,message,sizeof(message),priority);
printf("Your message with the priority %d has been successfully sent to int main (int argc,char* *args) {
the %s\n",priority,args[1]); struct mq_attr attr;
mq_close(mqdes); mqd_t mqdes;
return 0; void *buff;
//mq_close (mqdes); int priority;
} int n=0;
ReceiveMessage.c ReceiveMessage.c
if(argc!=2){ mq_getattr(mqdes,&attr);
fprintf(stderr,"Usage: %s <Message-Queue Name>\n",args[0]); buff=malloc(attr.mq_msgsize);
fprintf(stderr,"For Example #%s /myMQ\n",args[0]); n=mq_receive(mqdes,buff,attr.mq_msgsize,&priority);
exit(0); printf("The received message is as follows. Its priority is
} %d:\n%s",priority,buff);
printf("Press any key to terminate\n");
mqdes = mq_open (args[1], O_RDONLY); getchar();
if(mqdes==-1){ mq_close(mqdes);
printf("error: %s (%d)\n",strerror(errno),errno); return 0;
return 1; }
}
4
7/21/2017
• E.g.,
printf(“MQ_OPEN_MAX = %ld, MQ_PRIO_MAX= %ld\n”,
sysconf(_SC_MQ_OPEN_MAX),
sysconf(_SC_ MQ_PRIO_MAX));