多个进程通过消息队列进行通信,通过多个进程(至少3个;独立创建多个codeblocks程序),实现以下内容:1)消息队列及其管理(创建消息、插入消息和获取消息);2)进程之间关于消息队列的互斥与同步。不能使用系统自带的消息通信机制
2条回答 默认 最新
关注 尝试下下面代码:
代码如下:发送端:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/ipc.h> #include<sys/msg.h> struct mymesg{ long int mtype; char mtext[512]; }; int main(void) { int id = 0; struct mymesg ckxmsg; key_t key = ftok("/tmp",66); id = msgget(key,IPC_CREAT | 0666); if(id == -1){ printf("create msg error \n"); return 0; } while(1){ char msg[512]; memset(msg,0,sizeof(msg)); ckxmsg.mtype = 1; printf("input message:"); fgets(msg,sizeof(msg),stdin); strcpy(ckxmsg.mtext,msg); if(msgsnd(id,(void *)&ckxmsg,512,0) < 0){ printf("send msg error \n"); return 0; } if(strncmp(msg,"QUIT",4) == 0) break; } if(msgctl(id,IPC_RMID,NULL) < 0){ printf("del msg error \n"); return 0; } return 0; }
接收端:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/ipc.h> #include<sys/msg.h> struct mymesg{ long int mtype; char mtext[512]; }; int main(void) { int id = 0; struct mymesg ckxmsg; key_t key = ftok("/tmp",66); id = msgget(key,0666|IPC_CREAT); if(id == -1){ printf("open msg error \n"); return 0; } while(1){ if(msgrcv(id,(void *)&ckxmsg,512,1,0) < 0){ printf("receive msg error \n"); return 0; } printf("data:%s\n",ckxmsg.mtext); if(strncmp(ckxmsg.mtext,"QUIT",4) ==0) break; } return 0; }
如有问题,及时沟通。
如有帮助,欢迎点赞。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报 编辑记录无用 1
悬赏问题
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码
- ¥15 ubuntu子系统密码忘记
- ¥15 保护模式-系统加载-段寄存器