Monday, December 21, 2009

System V Message queue

System V Message Queue

Message Queue Sender Program
//-----------------------------------------------------------------//
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct my_msgbuf {
long mtype;
char mtext[1000];
//char mtext;
};

int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key = 2221;

if ((msqid = msgget(key, 0666 | IPC_CREAT)) < 0) {
perror("msgget");
exit(1);
}
printf("nmsgqid %dn", msqid);

buf.mtype = 1;
strcpy(buf.mtext,"hello world ");
size_t len = sizeof(struct my_msgbuf) - sizeof(long);
printf("len %dn", len);

struct msqid_ds buf_ds;
while(1)
{
sleep(2);
if (msgsnd(msqid, &buf, len, IPC_NOWAIT) < 0)
{
// if message queue is full increase the message queue size
if(msgctl(msqid, IPC_STAT, &buf_ds) < 0)
{
perror("msgctl:get");
exit(1);
}

buf_ds.msg_qbytes += 16*1024;
if(msgctl(msqid, IPC_SET, &buf_ds) < 0)
{
perror("msgctl:set");
exit(1);
}

if (msgsnd(msqid, &buf, len, IPC_NOWAIT) < 0)
{
perror("msgsnd");
exit(1);
}
}
}
return 0;
}
//-----------------------------------------------------------------//


Message Queue Receiver Program
//-----------------------------------------------------------------//
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>

#define MSGSZ 1000

/*Declare the message structure*/

typedef struct my_msgbuf {
long mtype;
char mtext[1000];
//char mtext;
} message_buf;

main()
{
int msqid;
key_t key;
message_buf rbuf;

/*
*Get the message queue id for the
* "name" 2221, which was created by
* the server.
*/
key = 2221;

if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
return (0);
}

while(1)
{
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
return(0);
}

/*Print the answer*/

printf("%sn", rbuf.mtext);
}
return (0);
}
//-----------------------------------------------------------------//

No comments:

Post a Comment