Message Queuing is a list of some messages. Users can add messages, read messages, and so on in Message Queuing. The message exists in the kernel and has a "queue id" to identify
Msgget function Syntax:
msgsnd function Syntax:
MSGRCV function Syntax:
Msgctl function Syntax:
Add message code:
/*MSGSND.C Adding Messages*/#include<sys/types.h>#include<sys/ipc.h>#include<sys/msg.h>#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#defineBuffer_size 512structmessage{LongMsg_type; Charmsg_text[buffer_size];};intMain () {intqid; key_t key; structmessage msg; /*generate standard keys based on different paths and keywords*/ if(Key = Ftok (".",'a')) == -1) {perror ("Ftok"); Exit (1); } /*Creating message Queues*/ if(qid = msgget (key, ipc_creat|0666)) == -1) {perror ("Msgget"); Exit (1); } printf ("Open Queue%d\n", qid); while(1) {printf ("Enter Some message to the queue:"); if(Fgets (Msg.msg_text, buffer_size, stdin) = =NULL) {Puts ("No message"); Exit (1); } Msg.msg_type=Getpid (); /*adding messages to Message Queuing*/ if(Msgsnd (qid, &msg, strlen (Msg.msg_text),0)) <0) {perror ("message Posted"); Exit (1); } if(STRNCMP (Msg.msg_text,"quit",4) ==0) { Break; }} exit (0);}
Program code to read the message:
/*msgrcv.c reading Messages*/#include<sys/types.h>#include<sys/ipc.h>#include<sys/msg.h>#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#defineBuffer_size 512structmessage{LongMsg_type; Charmsg_text[buffer_size];};intMain () {intqid; key_t key; structmessage msg; /*generate standard keys based on different paths and keywords*/ if(Key = Ftok (".",'a')) == -1) {perror ("Ftok"); Exit (1); } /*Creating message Queues*/ if(qid = msgget (key, ipc_creat|0666)) == -1) {perror ("Msgget"); Exit (1); } printf ("Open Queue%d\n", qid); Do { /*Read Message Queuing*/memset (Msg.msg_text,0, buffer_size); if(Msgrcv (QID, (void*) &msg, buffer_size,0,0) <0) {perror ("MSGRCV"); Exit (1); } printf ("The message from process%d:%s", Msg.msg_type, Msg.msg_text); } while(STRNCMP (Msg.msg_text,"quit",4));/*To remove a message queue from the system kernel*/ if((Msgctl (qid, ipc_rmid, NULL)) <0) {perror ("Msgctl"); Exit (1); } return 0;}
Message Queuing for Process communication