How to Write Program for Message Queue

To write a message queue for inter process communication.
Step by step Algorithm Procedure
1. Start the program.
2. Variables are declared.
3. Check the condition using if condition. If it is -1, open queue otherwise exit the process.
4. From the function main, call a function open a queue( ), passing ,message key values on parameter.
5. In the open queue calls system call msg get( ) which creates the message queue which on success returns qid an on failure returns -1.
6. On failure to create message queue the function open return -1 to function main( ).
7. Else if message queue is created successfully return qid to main( ). Display the message queue created.
8. Give the value for ‘m’ type x salary.
9. Call function send.msg( ) from main( ), passing qid & msg as parameters.
10. send msg( ) sends the message for all system call and which return -1 on failure.
11. Else return to main ( ). Print message send.
12. Terminate the program.
Source Coding Program Linux Rhel 5 Message queue
#include
#include
#include
#include
struct mymsgbuf
{
long mtype;
double salary;
} msg;
key_t_msgkey=4;
main( )
{
int qid;
if((qid=open_queue(msgkey))==-1)
{
perror(“Open Queue”);
exit(1);
}
else
{
printf(“Message queue created”);
}
msg.mtype=1;
msg.salary=1000.00;
if((send_message(qid, &msg)==-1)
{
perror(“Send Message”);
exit(1);
}
else
{
printf(“\n Message sent”);
}
int open_queue(key_t_keyval)
{
int qid;
if((qid=msgget(keyval, IPC_CREATE! 0666))==-1)
{
return(-1) ;
}
return(qid);
}
int send_message(int qid,struct mymsgbuf *gbuf)
{
int result,length;
length=sizeof(struct mymsgbuf);
if(result=msgsnd(qid, qbuf, length, 0)==1)
{
return(-1);
}
return(result);
}
Source Coding Program Linux Rhel 5 Message queue
#include
main( )
{
char *msg1= “hai”;
char *msg2= “hello”;
char *msg3= “thank u”;
char a[10]’
int p[2];
pipe(p);
write(p[1],msg1,15);
read(p[0],0.15);
a[15]= ‘\0’;
printf(“\n \t first message \n %s”, a);
write(p[1],msg2,15);
read(p[0],0.15);
a[15]= ‘\0’;
printf(“\n \t second message \n %s”, a);
write(p[1],msg3,15);
read(p[0],0.15);
a[15]= ‘\0’;
printf(“\n \t third message \n %s”, a);
}

Output
[staff@linux-router staff]$ gcc mq1.c
[staff@linux-router staff]$ ./a.out
Message queue created
Message sent
[staff@linux-router staff]$ gcc mq2.c
[staff@linux-router staff]$ ./a.out
first message
hai
second message
hello
third message
thank u
[staff@linux-router staff]$
Result: Thus a message queue was written for inter process communication.

Post a Comment

0 Comments