进程通信---消息队列

## 标题队列:先进先出

对数据进行分类(存储的时候分类) 操作:

1. 创建或者获取消息队列
1. 写入或者读取数据
2. 删除消息队列


## 标题创建或者获取消息队列:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
命令方式查看消息队列:
ipcs -q
功能:
创建或者获取消息队列
参数:
key : 参考共享内存
msgflg: IPC_CREAT|0666
返回值:
成功返回消息队列id号
失败返回-1 并设置error
*
标题写入或者读取数据:

## *写入:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
功能:
往消息队列中写入数据

- 参数:

msqid :
msgp : //结构体自已定义
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */ 可以 为所欲为
};

- msgsz : 数据的大小(除去类型) sizeof(struct msgbuf)-sizeof(long)

 

- msgflg : 0 可阻塞 IPC_NOWAIT不阻塞

返回值:
成功返回0
失败返回-1 并设置error


## 读
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
功能:
从消息队列中读取数据
参数:

- msqid ://参考共享内存

- msgp : struct msgbuf { //结构体自已定义跟写的一摸一样
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */ //可以 为所欲为 };

- msgsz:数据的大小(除去类型)
sizeof(struct msgbuf)-sizeof(long)

msgtyp:

- 读取的类型
=0, 整个队列的第一条数据.
>0, msgtyp类型的第一条数据
<0, 比 |msgtyp| 小的(等于) 最小类型的第一条数据

- msgflg: 0 可阻塞 IPC_NOWAIT不阻塞

- 返回值: 成功返回 数据的字节数(mtext) 失败返回-1 并设置error

## 例子
读的代码 msgget_w.c

 

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>

struct msgbuf {
long mtype; /* message type, must be > 0 */ //8
char mtext[100]; /* message data */ //可以 为所欲为 100
};
int main()
{
key_t key =ftok("xx.c",5);
if(key <0){
perror("ftok error");
}
printf("key:%#x\n",key);
//创建或者获取
int msqid = msgget(key,IPC_CREAT|0666);
if(msqid < 0){
perror("msgget error");
exit(-1);
}
printf("msqid:%d\n",msqid);

///写入数据
struct msgbuf sm;
sm.mtype = 3;
strcpy(sm.mtext,"yyyyyyy");
int ret =msgsnd(msqid,&sm,sizeof(struct msgbuf)-sizeof(long),0);
if(ret < 0){
perror("msgsnd error");
exit(-1);
}
return 0;
}


 读 msgget_r.c


#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>

struct msgbuf {
long mtype; /* message type, must be > 0 */ //8
char mtext[100]; /* message data */ //可以 为所欲为 100
};

int main()
{
key_t key =ftok("xx.c",5);
if(key <0){
perror("ftok error");
}
printf("key:%#x\n",key);

//创建或者获取消息队列
int msqid = msgget(key,IPC_CREAT|0666);
if(msqid<0){
perror("msgget error");
exit(-1);
}
printf("msqid:%d\n",msqid);

///读取数据
struct msgbuf sm;
int ret = msgrcv(msqid,&sm,sizeof(struct msgbuf)-sizeof(long),-4,0);
if(ret<0){
perror("msgrcv error");
exit(-1);
}
printf("%s\n",sm.mtext);
return 0;
}

2022-05-15 13:50:00

posted @ 2022-05-15 13:50  孤走  阅读(42)  评论(0编辑  收藏  举报