c语言消息队列的作用,C语言消息队列-消息类型不同的发送和接收

#include

#include

#include

#include

#include

#include

#include

#define BUF_SIZE 128

typedef struct mymsg

{

long mtype;

char mtext[BUF_SIZE];

}MSG;

void menu();

void send_msg(int msgid,MSG *msg);

void receive_msg(int msgid,MSG *msg);

void del_msg(int msgid);

int get_key()

{

int key;

key=ftok(".",'s');

}

int main()

{

MSG *msg;

key_t key;

int msgid;

int select;char get[3];

key=get_key();

if(key<0)

{

perror("get key error");

exit(1);

}

msgid=msgget(key,IPC_CREAT|0644);

if(msgid<0)

{

perror("msgget error");

exit(1);

}

printf("get msg success\n");

msg=(MSG *)malloc(sizeof(MSG));

if(msg==NULL)

{

perror("malloc error");

exit(1);

}

printf("\033[0;0H \033[2J");

do

{

menu();

printf("=====>>");

scanf("%s",get);

select=atoi(get);

switch(select)

{

case 1:send_msg(msgid,msg);

break;

case 2:receive_msg(msgid,msg);

break;

case 3:del_msg(msgid);

break;

case 4:return;

break;

default :exit(1);

}

}while(1);

return 0;

}

void menu()

{

printf("\t\t===========消息队列操作===========\n");

printf("\t\t1.发送消息\n");

printf("\t\t2.接收消息\n");

printf("\t\t3.销毁消息队列\n");

printf("\t\t4.退出操作界面\n");

}

void send_msg(int msgid,MSG *msg)//发送消息

{

MSG *current,*new_msg;

char t_name[20];int t_age;char str[80];

char c;

new_msg=(MSG *)malloc(sizeof(MSG));

printf("请输入消息类型\n");

c=getchar();

if(c='\n')

{

c=getchar();

}

if(c=='T')

{

new_msg->mtype='T';

printf("输入老师的姓名--->");

scanf("%s",t_name);

printf("输入老师的年龄-->");

scanf("%d",&t_age);

sprintf(str,"老师的姓名是:%s,老师的年龄是:%d",t_name,t_age);

strcpy(new_msg->mtext,str);

}

else if(c=='S')

{

new_msg->mtype='S';

printf("输入学生的姓名--->");

scanf("%s",t_name);

printf("输入学生的年龄-->");

scanf("%d",&t_age);

sprintf(str,"学生的姓名是:%s,学生的年龄是:%d",t_name,t_age);

strcpy(new_msg->mtext,str);

}

else

{

printf("输入有误\n");

return;

}

if(msgsnd(msgid,new_msg,BUF_SIZE,0)==-1)

{

perror("send msg error");

exit(1);

}

printf("send msg success\n");

}

void receive_msg(int msgid,MSG *msg)

{

char c;long type;

printf("请输入消息类型\n");

c=getchar();

if(c='\n')

{

c=getchar();

}

if(c=='T')

{

type='T';

}

else if(c=='S')

{

type='S';

}

else

{

printf("输入有误\n");

return;

}

printf("正在接收消息\n");

/*最后一个参数是0的时候,没有消息会被挂起,IPC_NOWAIT会在没有消息时返回-1*/

if(msgrcv(msgid,msg, BUF_SIZE,type,IPC_NOWAIT)==-1)

{

printf("rcv msg error\n");

exit(1);

}

else printf("Type:%c,Text:%s\n",(char)msg->mtype,msg->mtext);

}

void del_msg(int msgid)

{

if(msgctl(msgid,IPC_RMID,0)==-1)

{

perror("rm msg error");

exit(1);

}

printf("成功销毁消息队列\n");

exit(0);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值