现在的位置: 首页 > 综合 > 正文

消息队列实现进程间通信

2017年12月19日 ⁄ 综合 ⁄ 共 1346字 ⁄ 字号 评论关闭

服务器

 

  1. #include"sys/types.h" 
  2. #include"sys/msg.h" 
  3. #include"sys/ipc.h" 
  4. #define MSGKEY 75 
  5. struct msgform{ 
  6.     long mtype; 
  7.     char mtext[1000]; 
  8. }msg; 
  9.  
  10. void server() 
  11.     int msgid; 
  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("receive error!\n"); 
  23.             exit(0); 
  24.         } 
  25.         printf("recevied message succeed!\n"); 
  26.  
  27.     }while(msg.mtype!=1); 
  28.     if(msgctl(msgid,IPC_RMID,0)==-1) 
  29.     { 
  30.         printf("msgctl failed!\n"); 
  31.         exit(0); 
  32.     } 
  33.     exit(1); 
  34.  
  35. main() 
  36.     server(); 


客户端

 

  1. #include"sys/types.h" 
  2. #include"sys/msg.h" 
  3. #include"sys/ipc.h" 
  4. #define MSGKEY 75 
  5. struct msgform 
  6.     long mtype; 
  7.     char mtext[1000]; 
  8. }msg; 
  9.  
  10. void client() 
  11.     int msgid,i; 
  12.     msgid=msgget(MSGKEY,IPC_CREAT|00666); 
  13.     if(msgid==-1) 
  14.     { 
  15.         printf("open error!\n"); 
  16.         return
  17.     } 
  18.     for(i=10;i>=1;i--) 
  19.     { 
  20.         msg.mtype=i; 
  21.         printf("client sent message!\n"); 
  22.         if(msgsnd(msgid,(void*)&msg,1000,0)==-1) 
  23.         { 
  24.             printf("send error!\n"); 
  25.             exit(0); 
  26.         } 
  27.         printf("send message succeed!\n"); 
  28.     } 
  29.     exit(1); 
  30.  
  31. main() 
  32.     client(); 

 

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

【上篇】
【下篇】

抱歉!评论已关闭.