Showing posts with label message queue. Show all posts
Showing posts with label message queue. Show all posts

Tuesday, June 05, 2007

Message Queue example

The time to use Message Queue I know is internal logging, and that's the way it used.

msgq_rcv <- MSG Queue <- msgq_snd

sample code below,
msgq.h

#ifndef _MSGQ_H_
#define _MSGQ_H_

#define MSGQ_PATH "/tmp"
#define MSGQ_ID 111
#define MSG_LEN 128

typedef struct {
long mtype; // MUST
time_t time;
char msg[MSG_LEN+1];
} msgq_t ;

#endif /* _MSGQ_H_ */

msgq_rcv.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <time.h>
#include "msgq.h"

int main(int argc, char *argv[])
{
key_t key;
int msgqid;
msgq_t msg;

if ( (key=ftok(MSGQ_PATH, MSGQ_ID)) == -1) {
perror("ftok");
return -1;
}

if ( (msgqid = msgget(key, 0666|IPC_CREAT)) == -1) {
perror("msgget");
return -1;
}

while (1) {
if (-1==msgrcv(msgqid, &msg, sizeof(msg), 0, 0)) {
perror("msgrcv");
return -1;
}
printf("%s->%s\n", ctime(&msg.time), msg.msg);
}

return 0;
}

msgq_snd.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <time.h>
#include <string.h>
#include "msgq.h"

int main(int argc, char *argv[])
{
key_t key;
int msgqid;
msgq_t msg;

if ( (key=ftok(MSGQ_PATH, MSGQ_ID)) == -1) {
perror("ftok");
return -1;
}

if ( (msgqid = msgget(key, 0666|IPC_CREAT)) == -1) {
perror("msgget");
return -1;
}

while (1) {
memset(&msg, 0x00, sizeof(msg));
msg.mtype = 1; // MUST
fgets(msg.msg, sizeof(msg.msg)-1, stdin);
time(&(msg.time));
if (-1==msgsnd(msgqid, (msgq_t*)&msg, sizeof(msg), 0)) {
perror("msgsnd");
return -1;
}
}
}