Message Queueの使い方
戻る
::::::::::::::
mqtest.h
::::::::::::::
#define CONTENT_SIZE 512
typedef struct
{
long msgType;
char msgContent[CONTENT_SIZE];
} MSG_BUF;
::::::::::::::
mqreceiver.c
::::::::::::::
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "./mqtest.h"
int
main ()
{
int qid;
MSG_BUF buf;
if ((qid = msgget (123, 0666 | IPC_CREAT)) == -1) {
perror ("msgget");
exit (-1);
}
while (1) {
if (msgrcv (qid, &buf, CONTENT_SIZE, 0L, 0) == -1) {
perror ("msgrcv");
break;
}
printf ("%s\n", buf.msgContent);
if (strcmp (buf.msgContent, "end") == 0) {
break;
}
}
if (msgctl (qid, IPC_RMID, NULL) == -1) {
perror ("msgctl");
exit (-1);
}
return 0;
}
::::::::::::::
mqsender.c
::::::::::::::
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "./mqtest.h"
// $Id: mq.html,v 1.1 2009/06/22 16:12:17 kishi Exp kishi $
int
main ()
{
int qid;
MSG_BUF buf;
if ((qid = msgget (123, 0666 | IPC_CREAT)) == -1) {
perror ("msgget");
exit (-1);
}
while (1) {
gets (buf.msgContent);
buf.msgType = 1L;
if (msgsnd (qid, &buf, sizeof (buf.msgContent) - sizeof (buf.msgType), 0)
== -1) {
perror ("msgsnd");
break;
}
if (strcmp (buf.msgContent, "end") == 0) {
break;
}
}
return 0;
}
■実行結果 ( 事前に cygserverを起動する必要あり -- cygwinの場合 )
$ /usr/sbin/cygserver.exe &
$ ./mqreceiver.exe
123
456
q1w2e3r4t5y6u7
end
$ ./mqsender.exe
123
456
q1w2e3r4t5y6u7
end
戻る