msgget(): To create a message queue we use msgget() system call. It takes the following arguments.
semget(int key,msgflags);
ex: msgget(12344,IPC_CREAT|0666);
msgsnd(): This system call is used to place data in a message queue.
msgsnd(msqid, &sbuf, buflen,0); /* struct msgbuf sbuf */
msgrcv(): This system call is used to receive data from the message queue
msgrcv(msqid, &rcvbuffer, string length, 1, 0)
msgctl(): This system call is used to get the status information of the message queue or to remove the message queue
msgctl(int msgqid,int cmd,struct msgqid_ds *buf);
/* message queue program to send data on to message queue*/
#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;
char mtext[MAXSIZE];
};
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 123555;
if ((msqid = msgget(key, msgflg )) < 0) //Get the message queue ID for the given key
printf("eorror");
//Message Type
sbuf.mtype = 1;
printf("Enter a message to add to message queue : ");
scanf("%s",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf("error");
}
else
printf("Message Sent\n");
exit(0);
}
output: /home/anil~$ cc msgsnd.c
/home/anil~$ ./a.out
Enter a message to add to message queue: hi hello
Message Sent
/*message queue program to receive message from the message queue*/
#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];
};
main()
{
int msqid;
key_t key;
struct msgbuf rcvbuffer;
key = 123555;
if ((msqid = msgget(key, 0666)) < 0)
printf("message queue cannot be created");
//Receive an answer of message type 1.
if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
printf("\n error in reading the message from the message queue");
printf("%s", rcvbuffer.mtext);
exit(0);
}
output: /home/anil~$ cc msgq_rcv.c
/home/anil~$ ./a.out
hi hello
IPC using message queue, msgget(),msgsnd(),msgrcv() IPC flags, client server program to send and receive messages, message structure, mtype, ftok(),key_t key, <ipc/stat.h>. difference between pipes and message queue
No comments:
Post a Comment