日期:2014-05-16  浏览次数:20655 次

linux进程通信(二)--消息队列
C代码

   1. /*msgserver.c*/ 
   2.  
   3. #include <stdlib.h> 
   4. #include <string.h> 
   5. #include <errno.h> 
   6. #include <sys/types.h> 
   7. #include <sys/ipc.h> 
   8. #include <sys/msg.h> 
   9. #include <sys/stat.h> 
  10.  
  11. #define   MSG_FILE "msgserver.c"  
  12. #define   BUFFER 255  
  13. #define   PERM S_IRUSR|S_IWUSR  
  14. /* 服务端创建的消息队列最后没有删除,我们要使用ipcrm命令来删除的 */ 
  15. /* ipcrm -q <msqid> */ 
  16.  
  17. struct msgtype  
  18. {  
  19.     long mtype;  
  20.     char buffer[BUFFER+1];  
  21. };  
  22.  
  23. int main()  
  24. {  
  25.     struct msgtype msg;  
  26.     key_t key;  
  27.     int msgid;  
  28.      
  29.     if((key=ftok(MSG_FILE,'a'))==-1)  
  30.     {  
  31.         fprintf(stderr,"Creat Key Error:%s\n", strerror(errno));  
  32.         exit(1);  
  33.     }  
  34.  
  35.     if((msgid=msgget(key, PERM|IPC_CREAT|IPC_EXCL))==-1)  
  36.     { 
  37.         fprintf(stderr, "Creat Message Error:%s\n", strerror(errno));  
  38.         exit(1); 
  39.     }  
  40.     printf("msqid = %d\n", msgid); 
  41.     while(1) 
  42.     {  
  43.         msgrcv(msgid, &msg, sizeof(struct msgtype), 1, 0);  
  44.         fprintf(stderr,"Server Receive:%s\n", msg.buffer);  
  45.         msg.mtype = 2;  
  46.         msgsnd(msgid, &msg, sizeof(struct msgtype), 0);  
  47.     }  
  48.     exit(0);  
  49. }    
   1. /* msgclient.c */ 
   2.  
   3. #include <stdio.h> 
   4. #include <stdlib.h> 
   5. #include <string.h> 
   6. #include <errno.h> 
   7. #include <sys/types.h> 
   8. #include <sys/ipc.h> 
   9. #include <sys/msg.h> 
  10. #include <sys/stat.h> 
  11.  
  12. #define   MSG_FILE "msgserver.c"  
  13. #define   BUFFER 255  
  14. #define   PERM S_IRUSR|S_IWUSR  
  15.  
  16. struct msgtype {