函数
msgget()
int msgget(key_t key, int mode);
创建消息队列,或者获取消息队列
参数
- key:使用ftok()获取到的key
- mode:IPC_CREAT | 0644
返回
- 消息队列id
msgsnd()
- 会发生拷贝
- 往队列里发送消息,此操作被中断后不会被重启(信号处理中SA_RESTART)。
int msgsnd(int msgid, const void* msgp, size_t msgsz, int msgflg);
参数
msgid 消息队列id
msgp 消息,通常为下面结构体
struct msgbuf { long mtype; //消息类型,必须>0 char mtext[100]; //消息数据,可以自定义大小 };
msgsz 消息长度,指消息数据的长度
msgflg —— IPC_NOWAIT(不阻塞),MSG_EXCEPT(接收不检测mtype),MSG_NOERROR(消息数据过长时会截断数据)
返回:0表示成功,-1失败
msgrcv
- 从队列接收一个并移除一个消息。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtype,
int msgflg);
流程
- ftok()生产key
- msgget()获取消息队列
- msgsnd()发送消息 或者 msgrev接收消息
- msgctl() 删除消息队列
代码
接收消息代码
/*************************************************************************
> File Name: msg.c
> Author:
> Mail:
> Created Time: Sat 29 Jan 2022 07:04:18 PM CST
************************************************************************/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/msg.h>
#define MSG_MAX_TEXT 1024
typedef struct {
long mtype;
char mtext[MSG_MAX_TEXT];
} Msgbuf;
int main() {
//获取key值
key_t key = ftok("./msgTp", 233);
printf("key = 0x%x\n", key);
//创建消息队列
int msgid = msgget(key, IPC_CREAT | 0644);
if (msgid < 0) {
perror("msgget");
exit(1);
}
printf("msgid = %d\n", msgid);
Msgbuf msgbuf;
//接收消息
msgrcv(msgid, &msgbuf, MSG_MAX_TEXT, 1, 0);
printf("%s\n", msgbuf.mtext);
msgrcv(msgid, &msgbuf, MSG_MAX_TEXT, 2, 0);
printf("%s\n", msgbuf.mtext);
return 0;
}
发消息代码
/*************************************************************************
> File Name: msg.c
> Author:
> Mail:
> Created Time: Sat 29 Jan 2022 07:04:18 PM CST
************************************************************************/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/msg.h>
#define MSG_MAX_TEXT 1024
typedef struct {
long mtype;
char mtext[MSG_MAX_TEXT];
} Msgbuf;
int main() {
//获取key值
key_t key = ftok("./msgTp", 233);
printf("key = 0x%x\n", key);
//创建消息队列
int msgid = msgget(key, IPC_CREAT | 0644);
if (msgid < 0) {
perror("msgget");
exit(1);
}
printf("msgid = %d\n", msgid);
Msgbuf msgbuf;
msgbuf.mtype = 1;
strncpy(msgbuf.mtext, "hello boys", MSG_MAX_TEXT);
msgsnd(msgid, &msgbuf, MSG_MAX_TEXT, 0);
msgbuf.mtype = 2;
strncpy(msgbuf.mtext, "小明:onlike\n", MSG_MAX_TEXT);
msgsnd(msgid, &msgbuf, MSG_MAX_TEXT, 0);
return 0;
}