Sunday, March 11, 2012

INTER PROCESS COMMUNICATION USING MESSAGE QUEUE




Ex. No.: 7
INTER PROCESS COMMUNICATION USING MESSAGE QUEUE


AIM:
To write a C program to develop Inter Process Communication application using             Message queue.

PROBLEM DESCRIPTION:

Create a server program to create a message queue using msgget( ) system call. Create a dynamic structure containing the string and its type. Create a client program which reads a set of strings and stores them in the queue using msgsnd( ) system call. The server program reads the strings from the message queue using msgrcv( ) system call. It computes the number of vowels in the strings of first client.

SYSTEM CALLS USED:

Ø  msgget( ) –   to initialize a new message queue

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int msgget(key_t key, int msgflg);

Description

 
The function returns the message queue identifier associated with the value of the key argument.  A new message queue is created if key has the value IPC_PRIVATE or key isn’t IPC_PRIVATE, no message queue with the given key key exists, and IPC_CREAT is asserted in msgflg (i.e., msgflg & IPC_CREAT is nonzero). 
            
The presence in msgflg of the fields IPC_CREAT and IPC_EXCL plays the same role, with respect to the existence of the message queue, as the presence of O_CREAT and O_EXCL in the mode argument of the open (2) system call: i.e. the msgget function fails if  msgflg  asserts  both  IPC_CREAT and IPC_EXCL and a message queue already exists for key.
 
Upon creation, the lower 9 bits of the argument msgflg define the access permissions of the message queue.  These permission bits have the same format and semantics as the access permissions parameter in open (2) or create (2) system calls.  (The execute permissions are not used).
 
If the message queue already exists the access permissions are verified, and a check is made to see if it is marked for destruction. If successful, the return value will be the message queue identifier (a nonnegative integer), otherwise -1 with errno indicating the error.
 
 
 
Ø  msgsnd( ), msgrcv( )message operations

Synopsis

ssize_t msgrcv(int msqid, struct msgbuf *msgp, size_t msgsz, long msgtyp, int msgflg);

int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz, int msgflg);

Description

To send or receive a message, the calling process allocates a structure of the following general form:
            struct msgbuf {
                                     long mtype;     /* message type, must be > 0 */
                                     char mtext[1];  /* message data */
                                      };
 
The mtext field is an array (or other structure) whose size is specified by msgsz, a non-negative integer value. Messages of zero length (i.e., no mtext field) are permitted. The mtype field must have a strictly positive integer value that can be used by the receiving process for message selection.
 
The calling process must have write permission to send and read permission to receive a message on the queue.
 
The msgsnd system call appends a copy of the message pointed to by msgp to the message queue whose identifier is specified by msqid.
 
If sufficient space is available on the queue, msgsnd succeeds immediately. (The queue capacity is defined by the msg_bytes field in the associated data structure for the message queue.  During queue creation this field is initialized to MSGMNB bytes, but this limit can be modified using msgctl.) If insufficient space is available on the queue, then the default behavior of msgsnd is to block until space becomes available. If IPC_NOWAIT is asserted in msgflg then the call instead fails with the error EAGAIN.
 
Upon successful completion the message queue data structure is updated as follows:
§  msg_lspid is set to the process ID of the calling process.
 
The argument msgtyp specifies the type of message requested as follows:
 
§  If msgtyp is 0, then the first message in the queue is read.
§  If msgtyp is greater than 0, then  the  first  message  on  the queue of type msgtyp is read, unless MSG_EXCEPT was asserted in msgflg, in which case the first message on the  queue  of  type not equal to msgtyp will be read.
§  If msgtyp is less than 0, then the first message on the queue with the lowest type less than or equal to the absolute value of msgtyp will be read.
 
The  msgflg  argument  asserts  none, one or more (or-ing them) of the following flags:
 
§  IPC_NOWAIT For immediate return if no message of the requested type is on the queue. The system call fails with errno set to ENOMSG.
§  MSG_EXCEPT Used with msgtyp greater than 0 to read the first message on the queue with message type that differs from msgtyp.
§  MSG_NOERROR To truncate the message text if longer than  msgsz bytes.
Upon successful completion the message queue data structure is updated as follows:
§  msg_lrpid is set to the process ID of the calling process.
§  msg_qnum is decremented by 1.
§  msg_rtime is set to the current time.
On a failure both functions return -1 with errno indicating the error.
 
Ø  msgctl( ) message control operations

Synopsis
           int msgctl(int msqid, int cmd, struct msqid_ds *buf);

Description
This function performs the control operation specified by cmd on the message queue with identifier msqid.  Legal values for cmd are:

  • IPC_STAT: Copy info from the message queue data structure associated with msqid into the structure pointed to by buf.  The caller must have read permission on the message queue.

  • IPC_SET: Write the values of some members of the msqid_ds  structure pointed to by buf to the message queue data structure, updating also its msg_ctime member.  The following members of the structure can be updated:
                    msg_perm.uid
                         msg_perm.gid
msg_perm.mode  /* only lowest 9-bits */
                        msg_qbytes

  • IPC_RMID: Immediately  remove  the  message queue and its associated data structure, awakening all waiting reader  and  writer  processes (with  an  error  return  and errno set to EIDRM).  The calling process must have appropriate (probably, root) privileges or its effective user-ID must be either that of the creator or owner of the message queue.
                  On success, the return value will be 0, otherwise -1 with errno indicating the error.

 ipcs Commands:-
The ipcs command can be used to obtain the status of all System IPC objects.
ipcs –q                        :    Show only message queues
ipcs –s             :    Show only semaphores
ipcs –m                       :    Show only shared memory
ipcs –help       :    Additional arguments
The ipcs command is a very powerful tool which provides a peek into the kernel's storage mechanisms for IPC objects.

//SERVER PROGRAM
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>

struct msgbuf {
  int mtype;
  char mtext[40];
}*msgp;

int main()
   {
      char str[40],rstr[40];
      int msgid,i,l,count,flag=0;
      int t;

      msgid=msgget(512, 0700 | IPC_CREAT | IPC_EXCL);
      printf("\nServer Message ID : %d \n", msgid);

      if(msgid==-1)
         {
            printf("Message Queue cannot be created\n");
            exit(0);
         }

      msgp=((struct msgbuf*)malloc(sizeof(struct msgbuf)));

      while(1)
      {
         count=0;

         msgrcv(msgid,msgp,sizeof(struct msgbuf),0,0);

         l=strlen(msgp->mtext);
         t = msgp -> mtype;
         strcpy(str,msgp->mtext);
          printf("\nProcessing Client1 data\n\n");
          if (strcmp(str,"NULL")==0)
             flag++;
              else
                {
                for(i=0;i<l;i++)
                if((str[i]=='a')||(str[i]=='e')
                      ||(str[i]=='i')||(str[i]=='o')
                      ||(str[i]=='u'))
                   count++;
             printf("The no. of vowels in the string %s is %d\n\n",str,count);

         } //switch
         if (flag==1)
            break;
     }
     msgctl(msgid,IPC_RMID,NULL);
 }

[jeyakumar@localhost ~]$ cc ser.c
[jeyakumar@localhost ~]$ ./a.out

Server Message ID : 0

Processing Client1 data

The no. of vowels in the string apple is 2

Processing Client1 data

The no. of vowels in the string orange is 3

Processing Client1 data

[jeyakumar@localhost ~]$


/* CLIENT PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct msgbuf
{
  int mtype;
  char mtext[40];
   }*msgp;

int main()
   {
      int msgid;
      char str[40];

      msgid=msgget(512,0700);
      printf("\nClient1 msgID : %d \n", msgid);
      if(msgid==-1)
         {
             printf("Message Queue does not exist\n");
             exit(0);
         }
      msgp=((struct msgbuf *)malloc(sizeof(struct msgbuf)));

      printf("\nClient1 Data - To Count Vowels\n\n");
      printf("Enter String to end type NULL\n\n");
      do
         {
            scanf("%s",str);
            strcpy(msgp->mtext,str);
            msgp->mtype=1;
            msgsnd(msgid,msgp,sizeof(struct msgbuf),0);
         }
      while(strcmp(str,"NULL")!=0);
    }

"cl1.c" 36L, 757C written
[jeyakumar@localhost ~]$ cc cl1.c
[jeyakumar@localhost ~]$ ./a.out

Client1 msgID : 0

Client1 Data - To Count Vowels

Enter String to end type NULL

apple
orange
NULL
[jeyakumar@localhost ~]$


RESULT:
Thus the C programs were written to implement the inter Process Communication application using message queue. The program was executed and its output was verifed successfully.

No comments:

Post a Comment

Slider

Image Slider By engineerportal.blogspot.in The slide is a linking image  Welcome to Engineer Portal... #htmlcaption

Tamil Short Film Laptaap

Tamil Short Film Laptaap
Laptapp

Labels

About Blogging (1) Advance Data Structure (2) ADVANCED COMPUTER ARCHITECTURE (4) Advanced Database (4) ADVANCED DATABASE TECHNOLOGY (4) ADVANCED JAVA PROGRAMMING (1) ADVANCED OPERATING SYSTEMS (3) ADVANCED OPERATING SYSTEMS LAB (2) Agriculture and Technology (1) Analag and Digital Communication (1) Android (1) Applet (1) ARTIFICIAL INTELLIGENCE (3) aspiration 2020 (3) assignment cse (12) AT (1) AT - key (1) Attacker World (6) Basic Electrical Engineering (1) C (1) C Aptitude (20) C Program (87) C# AND .NET FRAMEWORK (11) C++ (1) Calculator (1) Chemistry (1) Cloud Computing Lab (1) Compiler Design (8) Computer Graphics Lab (31) COMPUTER GRAPHICS LABORATORY (1) COMPUTER GRAPHICS Theory (1) COMPUTER NETWORKS (3) computer organisation and architecture (1) Course Plan (2) Cricket (1) cryptography and network security (3) CS 810 (2) cse syllabus (29) Cyberoam (1) Data Mining Techniques (5) Data structures (3) DATA WAREHOUSING AND DATA MINING (4) DATABASE MANAGEMENT SYSTEMS (8) DBMS Lab (11) Design and Analysis Algorithm CS 41 (1) Design and Management of Computer Networks (2) Development in Transportation (1) Digital Principles and System Design (1) Digital Signal Processing (15) DISCRETE MATHEMATICS (1) dos box (1) Download (1) ebooks (11) electronic circuits and electron devices (1) Embedded Software Development (4) Embedded systems lab (4) Embedded systems theory (1) Engineer Portal (1) ENGINEERING ECONOMICS AND FINANCIAL ACCOUNTING (5) ENGINEERING PHYSICS (1) english lab (7) Entertainment (1) Facebook (2) fact (31) FUNDAMENTALS OF COMPUTING AND PROGRAMMING (3) Gate (3) General (3) gitlab (1) Global warming (1) GRAPH THEORY (1) Grid Computing (11) hacking (4) HIGH SPEED NETWORKS (1) Horizon (1) III year (1) INFORMATION SECURITY (1) Installation (1) INTELLECTUAL PROPERTY RIGHTS (IPR) (1) Internal Test (13) internet programming lab (20) IPL (1) Java (38) java lab (1) Java Programs (28) jdbc (1) jsp (1) KNOWLEDGE MANAGEMENT (1) lab syllabus (4) MATHEMATICS (3) Mechanical Engineering (1) Microprocessor and Microcontroller (1) Microprocessor and Microcontroller lab (11) migration (1) Mini Projects (1) MOBILE AND PERVASIVE COMPUTING (15) MOBILE COMPUTING (1) Multicore Architecute (1) MULTICORE PROGRAMMING (2) Multiprocessor Programming (2) NANOTECHNOLOGY (1) NATURAL LANGUAGE PROCESSING (1) NETWORK PROGRAMMING AND MANAGEMENT (1) NETWORKPROGNMGMNT (1) networks lab (16) News (14) Nova (1) NUMERICAL METHODS (2) Object Oriented Programming (1) ooad lab (6) ooad theory (9) OPEN SOURCE LAB (22) openGL (10) Openstack (1) Operating System CS45 (2) operating systems lab (20) other (4) parallel computing (1) parallel processing (1) PARALLEL PROGRAMMING (1) Parallel Programming Paradigms (4) Perl (1) Placement (3) Placement - Interview Questions (64) PRINCIPLES OF COMMUNICATION (1) PROBABILITY AND QUEUING THEORY (3) PROGRAMMING PARADIGMS (1) Python (3) Question Bank (1) question of the day (8) Question Paper (13) Question Paper and Answer Key (3) Railway Airport and Harbor (1) REAL TIME SYSTEMS (1) RESOURCE MANAGEMENT TECHNIQUES (1) results (3) semester 4 (5) semester 5 (1) Semester 6 (5) SERVICE ORIENTED ARCHITECTURE (1) Skill Test (1) software (1) Software Engineering (4) SOFTWARE TESTING (1) Structural Analysis (1) syllabus (34) SYSTEM SOFTWARE (1) system software lab (2) SYSTEMS MODELING AND SIMULATION (1) Tansat (2) Tansat 2011 (1) Tansat 2013 (1) TCP/IP DESIGN AND IMPLEMENTATION (1) TECHNICAL ENGLISH (7) Technology and National Security (1) Theory of Computation (3) Thought for the Day (1) Timetable (4) tips (4) Topic Notes (7) tot (1) TOTAL QUALITY MANAGEMENT (4) tutorial (8) Ubuntu LTS 12.04 (1) Unit Wise Notes (1) University Question Paper (1) UNIX INTERNALS (1) UNIX Lab (21) USER INTERFACE DESIGN (3) VIDEO TUTORIALS (1) Virtual Instrumentation Lab (1) Visual Programming (2) Web Technology (11) WIRELESS NETWORKS (1)

LinkWithin