/*msgrcv函数从消息队列接受一个消息*/
//第一个参数为消息队列的标示符msgid
//第二个参数为指针,只想准备发送的消息
//第三个为指针,指向消息长度
//第四个为实现接受优先级的简单方式
//第五个为控制着没有相应类型的消息可供接受时将要发生的事情
//成功返回实际放到接受缓冲区里去的字符个数,失败返回-1
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m)
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
//第四个参数msgtype,表示接受消息类型号,无设置时表示按顺序接受
//第五个参数msgflg= MSG_NOERROR,消息大小超过msgsz时被截断
//消息结构体,一方面大小需小于系统限制MSGMAX,另外需以long/int长整形开始
/*消息结构体*/
struct msgbuf{
long mtype;//占四个字节
char mtext[1];
}
#define MSGMAX 8192
/* ./msg_rcv -n -t 2 *///与getopt有关
//从前向后读参数存入argv[1],argv[2].....
int main(int argc, char* argv[])
{
int flag = 0;
int type = 0;
int opt;
while(1){
opt= getopt(argc, argv, "nt:");
if(opt == '?')
exit(EXIT_FAILURE);
if(opt == -1)
break;
switch(opt)
{
case 'n':
/*printf("AAAA\n");*/
flag |= IPC_NOWAIT;//执行时添加-n参数表示非阻塞接受,出现错误时直接报错终止
//阻塞接受为程序运行阻塞至此
break;
case 't':
//printf("BBB\n");
type = atoi(optarg);//-t参数后可添加接受消息类型好
//printf("n = %d\n", n);
break;
}
}
int msgid;
msgid = msgget(1234, 0666 | IPC_CREAT | IPC_EXCL);
msgid = msgget(1234, 0);//0可以打开任何权限的消息队列,只打开不创建
if(msgid == -1)
{
ERR_EXIT("msgget");
}
printf("msgget success\n");
struct msgbuf *ptr;//消息结构体
ptr = (struct msgbuf*)malloc(sizeof(long)+MSGMAX);
ptr->mtype = type;//mtext未设置,即发送任意消息
int n;
if((n=msgrcv(msgid, ptr, MSGMAX, type, flag))<0)//当消息大于限制时,flag阻塞/非阻塞接受
{
ERR_EXIT("msgrcv");
}
printf("read %d bytes type=%ld\n", n, ptr->mtype);
return 0;
}
system v消息队列msgrcv函数
最新推荐文章于 2025-03-18 20:28:51 发布