Message
queues are one of the three IPC (Inter Process Communication) facilities
provided by the UNIX operating system apart from semaphores and shared memory.
Message queues appeared in an early release of UNIX system V release III as a
means of passing messages between processes in an asynchronous way.
Client and Server Program for Message Queue
Client Program Reads the Message from the Message Queue - receiver.
#include “sys/types.h”
#include “sys/ipc.h”
#include “sys/msg.h”
#include “stdio.h”
#define MSGSZ 128
typedef struct msgbuf {
long
mtype;
char
mtext[MSGSZ];
} message_buf;
main()
{
int msqid;
key_t key;
message_buf
rbuf;
printf("\n\tLab program 10 : Message
Queue - Reading content from the queue\n");
key = 10;
if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
exit(1);
}
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0)
< 0) {
perror("msgrcv");
exit(1);
}
printf("\nThe Message read from the
Message Queue : %s\n", rbuf.mtext);
exit(0);
}
____________________________________________________
Server Program stores Message into the Message Queue - Sender Program.
#include “sys/types.h”
#include “sys/ipc.h”
#include “sys/msg.h”
#include “stdio.h”
#include “string.h”
#include “fcntl.h”
#include “unistd.h”
#include “stdlib.h”
#define MSGSZ 128
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int
msqid;
int
msgflg = IPC_CREAT | 0666;
key_t key;
message_buf sbuf;
size_t buf_length;
char tmsg[100];
key
= 10;
printf("\n\tLab 10 : Message Queue - Sending Message to the Message
Queue\n\n");
printf("\nEnter a line to store as Message in the Queue : ");
fgets(tmsg,100,stdin);
printf("\nCalling
msgget with key %#lx and flag %#o\n",key,msgflg);
if
((msqid = msgget(key, msgflg )) < 0) {
perror("msgget");
exit(1);
}
else
printf("\nmsgget: msgget succeeded: msqid = %d\n", msqid);
sbuf.mtype = 1;
printf("\nmsgget: msgget succeeded: msqid = %d\n", msqid);
(void) strcpy(sbuf.mtext,tmsg);
printf("\nmsgget: msgget succeeded: msqid = %d\n", msqid);
buf_length = strlen(sbuf.mtext) + 1 ;
if
(msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {
printf ("\n%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext,
buf_length);
perror("msgsnd");
exit(1);
}
else
printf("\nMessage: \"%s\" Sent\n", sbuf.mtext);
exit(0);
}
No comments:
Post a Comment