-->

Wednesday, 24 January 2018

IPC Message Queue Implementation in C

IPC Message Queue Implementation in C

Image result for message queue






A simple implementation of IPC Message Queues.
IPC_msgq_send.c adds the message on the message queue .
IPC_msgq_rcv.c removes the message from the message queue.

To use this program first compile and run send.c to add a message to the message queue. To see the Message Queue type ipcs -q on your Unix/Linux Terminal.

Now compile and run rcv.c to read the message from the Message Queue.
To see that you have read the message again use ipcs -q 

Sender program:
File name: 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
void die(char *s)
{
  perror(s);
  exit(1);
}
typedef 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 = 1234;
    if ((msqid = msgget(key, msgflg )) < 0)   //Get the message queue ID for the given key
      die("msgget");
    //Message Type
    sbuf.mtype = 1;
    printf("Enter a message to add to message queue : ");
    scanf("%[^\n]",sbuf.mtext);
    getchar();
    buflen = strlen(sbuf.mtext) + 1 ;
    if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
    {
        printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
        die("msgsnd");
    }
    else
        printf("Message Sent\n");
    exit(0);
}


Receiver program:
File name: rcv.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE     128
void die(char *s)
{
  perror(s);
  exit(1);
}
typedef struct msgbuf
{
    long    mtype;
    char    mtext[MAXSIZE];
} ;
main()
{
    int msqid;
    key_t key;
    struct msgbuf rcvbuffer;
    key = 1234;
    if ((msqid = msgget(key, 0666)) < 0)
      die("msgget()");
     //Receive an answer of message type 1.
    if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
      die("msgrcv");
    printf("%s\n", rcvbuffer.mtext);
    exit(0);
}

keep calm and say bujuku bujuku.

0 comments:

Post a Comment

Start Work With Me

Contact Us
KUTTY SELVA
+91 7708139984
Madurai,Tamilnadu