mq.c
#include <stdio.h>
#include <ctype.h>#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#define MAX_SEND_SIZE 80
struct mymsgbuf{
long mtype;
char mtext[MAX_SEND_SIZE];
};
void send_message(int qid, struct mymsgbuf *qbuf, long type, char *text);
void read_message(int qid, struct mymsgbuf *qbuf, long type);
void change_queue_mode(int qid, char *mode);
void remove_queue(int qid);
void usage(void);
int main(int argc, char* argv[])
{
key_t key;
int msgqueue_id;
struct mymsgbuf qbuf;
if (argc == 1)
usage();
key = ftok(".",'m');
if ((msgqueue_id = msgget(key, IPC_CREAT|0660))==-1)
{
perror("msgget");
exit(1);
}
switch(tolower(argv[1][0]))
{
case 's':
send_message(msgqueue_id, (struct mymsgbuf *)&qbuf, atol(argv[2]),argv[3]);
break;
case 'r':
read_message(msgqueue_id, &qbuf, atol(argv[2]));
break;
case 'd':
remove_queue(msgqueue_id);
break;
case 'm':
change_queue_mode(msgqueue_id, argv[2]);
break;
default:usage();
}
return 0;
}
void send_message(int qid, struct mymsgbuf *qbuf, long type, char *text)
{
printf("sending a message...\n");
qbuf->mtype = type;
strcpy(qbuf->mtext, text);
if ((msgsnd(qid, (struct msgbuf *)qbuf, strlen(qbuf->mtext)+1,0))==-1)
{
perror("msgsnd");
exit(1);
}
}
void read_message(int qid, struct mymsgbuf *qbuf, long type)
{
printf("reading a message...\n");
qbuf->mtype = type;
msgrcv(qid, (struct msgbuf *)qbuf, MAX_SEND_SIZE, type, 0);
printf("Type : %ld Text:%s\n", qbuf->mtype, qbuf->mtext);
}
void change_queue_mode(int qid, char *mode)
{
struct msqid_ds myqueue_ds;
msgctl(qid, IPC_STAT, &myqueue_ds);
sscanf(mode, "%ho", &myqueue_ds.msg_perm.mode);
msgctl(qid, IPC_SET, &myqueue_ds);
}
void remove_queue(int qid)
{
msgctl(qid, IPC_RMID, 0);
}
void usage(void)
{
fprintf(stderr, "msgtool - A utility for tinkering whit msg queues\n");
fprintf(stderr, "\nUSAGE:msgtool (s)end<type><messagetext>\n");
fprintf(stderr, " (r)ecv<type>\n");
fprintf(stderr, " (d)elete\n");
fprintf(stderr, " (m)ode<octal mode>\n");
exit(1);
}
发送消息:
mq s (type) text
取得消息:
mq r (type)
修改权限:
mq m (mode)
删除消息队列:
mq d
#cc mq.c -o mq -g
#./mq s 1 tt
sending a message...
#./mq s 1 t2
sending a message...
#./mq s 2 tt
sending a message...
#./mq r 1
reading a message...
Type : 1 Text:tt
#./mq r 2
reading a message...
Type : 2 Text:tt
#./mq r 1
reading a message...
Type : 1 Text:t2