消息队列实现进程间通信

服务器

 
  1. #include"sys/types.h"
  2. #include"sys/msg.h"
  3. #include"sys/ipc.h"
  4. #defineMSGKEY75
  5. structmsgform{
  6. longmtype;
  7. charmtext[1000];
  8. }msg;
  9. voidserver()
  10. {
  11. intmsgid;
  12. msgid=msgget(MSGKEY,IPC_CREAT|00666);/*创建一个消息队列*/
  13. if(msgid==-1)
  14. {
  15. printf("error!\n");
  16. return;
  17. }
  18. do
  19. {
  20. if(msgrcv(msgid,(void*)&msg,1000,0,0)==-1)
  21. {
  22. printf("receiveerror!\n");
  23. exit(0);
  24. }
  25. printf("receviedmessagesucceed!\n");
  26. }while(msg.mtype!=1);
  27. if(msgctl(msgid,IPC_RMID,0)==-1)
  28. {
  29. printf("msgctlfailed!\n");
  30. exit(0);
  31. }
  32. exit(1);
  33. }
  34. main()
  35. {
  36. server();
  37. }

客户端

 
  1. #include"sys/types.h"
  2. #include"sys/msg.h"
  3. #include"sys/ipc.h"
  4. #defineMSGKEY75
  5. structmsgform
  6. {
  7. longmtype;
  8. charmtext[1000];
  9. }msg;
  10. voidclient()
  11. {
  12. intmsgid,i;
  13. msgid=msgget(MSGKEY,IPC_CREAT|00666);
  14. if(msgid==-1)
  15. {
  16. printf("openerror!\n");
  17. return;
  18. }
  19. for(i=10;i>=1;i--)
  20. {
  21. msg.mtype=i;
  22. printf("clientsentmessage!\n");
  23. if(msgsnd(msgid,(void*)&msg,1000,0)==-1)
  24. {
  25. printf("senderror!\n");
  26. exit(0);
  27. }
  28. printf("sendmessagesucceed!\n");
  29. }
  30. exit(1);
  31. }
  32. main()
  33. {
  34. client();
  35. }

本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/718898

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值