28 February, 2015

Network Programing: Practical#3

Aim: Programs related to message queues.
Theory:
//Program for Sender side
#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);
}

struct msgbuf
{
    long    mtype;
    char    mtext[MAXSIZE];
};

void 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, %li, %s, %li\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
        die("msgsnd");
    }

    else
        printf("Message Sent\n");

    exit(0);
}


//Program for Receiver side
#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);
}
static struct msgbuf
{
    long    mtype;
    char    mtext[];
};

void 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);
}



Firstly run this program on unix system then write it on the files...Take screen shots and then paste on the files for output...Do it in proper way and also understand the proper functioning... This is for I1 group only.....

No comments:

Post a Comment