消息队列
- msgget msgop msgctl
NAME
msgget - get a System V message queue identifier
msgrcv, msgsnd - System V message queue operations
msgctl - System V message control operations
SYNOPSIS
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
int msgflg);
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
消息队列使用实例
协议文件 proto.h
#ifndef PROTO_H__
#define PROTO_H__
#define NAMESIZE 64
#define KEYPATH "/etc/services"
#define KEYPROJ 'g'
struct msg_st
{
long mtype;
char name[NAMESIZE];
int math;
int chinese;
};
#endif
发送方 snder.h
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include "proto.h"
int main(){
key_t key;
int msgid;
struct msg_st sbuf;
key = ftok(KEYPATH, KEYPROJ);
if(key < 0){
perror("ftok:");
exit(1);
}
msgid = msgget(key, 0);
if(msgid < 0){
perror("msgget:");
exit(1);
}
sbuf.mtype = 1;
strcpy(sbuf.name, "Alan");
sbuf.math = rand()%100;
sbuf.chinese = rand()%100;
if(msgsnd(msgid, &sbuf, sizeof(sbuf)-sizeof(long), 0) < 0){
perror("msgrcv:");
exit(1);
}
puts("OK!");
exit(0);
}
接收方 rcver.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "proto.h"
int main(){
key_t key;
int msgid;
struct msg_st rbuf;
key = ftok(KEYPATH, KEYPROJ);
if(key < 0){
perror("ftok:");
exit(1);
}
msgid = msgget(key, IPC_CREAT|0600);
if(msgid < 0){
perror("msgget:");
exit(1);
}
while(1){
if(msgrcv(msgid, &rbuf, sizeof(rbuf)-sizeof(long), 0, 0) < 0){
perror("msgrcv:");
exit(1);
}
printf("NAME = %s\n", rbuf.name);
printf("MATH = %d\n", rbuf.math);
printf("CHINESE = %d\n", rbuf.chinese);
printf("\n");
}
msgctl(msgid, IPC_RMID, NULL);
exit(0);
}
先运行 接收方循环等待消息队列,再运行发送方向队列中发送消息。