Message Queue - MCA - System Software Lab
#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);
}
The above is the program to read the message from the message Queue acting as a Client program.#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);
}
The above is the program for storing content in the message Queue acting as Server program.
No comments:
Post a Comment