Networking Laboratory Day-1.
Networking Laboratory Day-1.
Message Queue:
- Data stream preserving message boundaries.
- Allows multiple processes to read/write without direct connection.
- Asynchronous communication: Sender and receiver don't need to interact simultaneously.
- Messages stored until retrieved by the recipient.
- Message boundary: Separation between messages in a protocol.
COMMANDS :
msgget(): either returns the message queue identifier for a newly created message queue or returns
the identifiers for a queue which exists with the same key value.
msgsnd(): Data is placed on to a message queue by calling msgsnd(). msgrcv(): messages are
retrieved from a queue.
msgctl(): It performs various operations on a queue. Generally it is use to destroy message queue.
IPC_CREAT | 0666 for a server (i.e., creating and granting read and write access to the server).
IPC_NOWAIT: If the message queue is full, then the message is not written to the queue, and
control is returned to the calling process. If not specified, then the calling process will suspend
(block) until the message can be written.
CODE :
//IPC_msgg_send.c :
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 128
struct msgbuf
{
long mtype; /* message type, must be > 0 */
char mtext[MAXSIZE];
};
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1234;
if ((msqid = msgget(key, msgflg)) < 0)
die("msgget");
printf("Enter A Message To Add To Message Queue And '0' To Quit.\n");
while (1)
{
sbuf.mtype = 1;
printf("Enter : ");
scanf(" %[^\n]", sbuf.mtext);
getchar();
if (strcmp(sbuf.mtext,"0")==0)
break;
buflen = strlen(sbuf.mtext) + 1;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf("%d, %ld, %s, %ld\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
else
printf("Message Sent\n");
}
exit(0);
}
OUTPUT :
/IPC_msgg_rcv.c :
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 128
struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
};
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
int msqid;
key_t key;
struct msgbuf rcvbuffer;
key = 1234;
if ((msqid = msgget(key, 0666)) < 0)
die("msgget()");
while (1)
{
if(msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
die("msgrcv");
printf("Received message: %s\n", rcvbuffer.mtext);
}
exit(0);
}
OUTPUT :