linux 消息序列(进程间通信)

来源:互联网 发布:淘一兔淘宝信誉查询 编辑:程序博客网 时间:2024/06/09 14:47

linux 消息序列(进程间通信)

分类: 文章 108人阅读 评论(0) 收藏 举报
[cpp] view plaincopyprint?
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4. #include <errno.h>  
  5. #include <unistd.h>  
  6. #include <sys/types.h>  
  7. #include <sys/ipc.h>  
  8. #include <sys/msg.h>  
  9.   
  10.   
  11. //需要自己定义的消息队列结构  
  12. struct msgStuct  
  13. {  
  14.   long int msgType;  
  15.   char strMsg[1024];  
  16. };  
  17.   
  18. int  
  19. main ()  
  20. {  
  21.   struct msgStuct msg_data;  
  22.   int msgid;  
  23.   char buffer[1024];  
  24.   //创建一个消息队列  
  25.   if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)  
  26.     {  
  27.       perror ("msgget failed with error: %d\n");  
  28.       exit (EXIT_FAILURE);  
  29.     }  
  30.   while (1)  
  31.     {  
  32.       printf ("Send message: ");  
  33.       fgets (buffer, 1024, stdin);  
  34.     //初始化消息类型  
  35.       msg_data.msgType = 1;  
  36.       strcpy (msg_data.strMsg, buffer);  
  37.     //发送消息  
  38.       if (msgsnd (msgid, (void *) &msg_data, 1024, 0) == -1)  
  39.     {  
  40.       fprintf (stderr, "msgsnd failed\n");  
  41.       exit (EXIT_FAILURE);  
  42.     }  
  43.       if (strncmp (buffer, "end", 3) == 0)  
  44.     {  
  45.       break;  
  46.     }  
  47.     }  
  48.   exit (EXIT_SUCCESS);  
  49. }  


[cpp] view plaincopyprint?
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4. #include <errno.h>  
  5. #include <unistd.h>  
  6. #include <sys/types.h>  
  7. #include <sys/ipc.h>  
  8. #include <sys/msg.h>  
  9.   
  10. //需要自己定义的消息队列结构  
  11. struct msgStuct  
  12. {  
  13.   long int msgType;  
  14.   char strMsg[1024];  
  15. };  
  16.   
  17. int  
  18. main ()  
  19. {  
  20.   int msgid;  
  21.   struct msgStuct msg_data;  
  22.   //接收消息优先级  
  23.   long int msgPriority = 0;//从队列中取第一个  
  24.   //创建一个消息队列  
  25.   if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)//类似open()创建一个文件返回它的文件描述符,这里是消息序列  
  26.     {  
  27.       perror ("msgget failed with error");  
  28.       exit (EXIT_FAILURE);  
  29.     }  
  30.   while (1)  
  31.     {  
  32.     //接收消息  
  33.       if (msgrcv (msgid, (void *) &msg_data, 1024,  
  34.           msgPriority, 0) == -1)  
  35.     {  
  36.       perror ("msgrcv failed with error");  
  37.       exit (EXIT_FAILURE);  
  38.     }  
  39.       printf ("Received message: %s", msg_data.strMsg);  
  40.       if (strncmp (msg_data.strMsg, "end", 3) == 0)  
  41.     {  
  42.       break;  
  43.     }  
  44.     }  
  45.   //删除消息队列  
  46.   if (msgctl (msgid, IPC_RMID, 0) == -1)  
  47.     {  
  48.       fprintf (stderr, "delete messagequeue error\n");  
  49.       exit (EXIT_FAILURE);  
  50.     }  
  51.   exit (EXIT_SUCCESS);  
  52. }  

第一个是send.c,第二个是recieve.c
原创粉丝点击