Linux -进程通信

一.概念

       消息队列提供了一种从一个进程向另一个进程发送一个数据块的方法。  每个数据块都被认为是有一个类型,接收者进程接收的数据块可以有不同的类型值。我们可以通过发送消息 来避免命名管道的同步和阻塞问题。消息队列与管道不同的是,消息队列是基于消息的, 而管道是基于字节流的,且消息队列的读取不⼀定是先入先出。消息队列与命名管道有一样的不足,就是每个消息的最大长度是有上限的(MSGMAX),每个消息队列的总的字节数是有上限的(MSGMNB),系统上消息队列的总数也有⼀个上限(MSGMNI)。

查看机器的三个上限值:



二. IPC对象数据结构

内核为每个IPC对象维护⼀一个数据结构(/usr/include/linux/ipc.h)

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. struct ipc_perm   
  2. {   
  3.     key_t  __key;  /* Key supplied to xxxget(2) */  
  4.    uid_t  uid;         /* Effective UID of owner */   
  5.     gid_t  gid;         /* Effective GID of owner */   
  6.     uid_t  cuid;        /* Effective UID of creator */   
  7.     gid_t  cgid;        /* Effective GID of creator */   
  8.     unsigned short  mode;        /* Permissions */   
  9.     unsigned short  __seq;       /* Sequence number */ };   

消息队列,共享内存和信号量都有这样⼀一个共同的数据结构。 


三、消息队列结构(/usr/include/linux/msg.h)

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* Obsolete, used only for backwards compatibility and libc5 compiles */  
  2. struct msqid_ds {  
  3.     <span style="color:#FF0000;">struct ipc_perm msg_perm;</span>  
  4.     struct msg *msg_first;      /* first message on queue,unused  */  
  5.     struct msg *msg_last;       /* last message in queue,unused */  
  6.     __kernel_time_t msg_stime;  /* last msgsnd time */  
  7.     __kernel_time_t msg_rtime;  /* last msgrcv time */  
  8.     __kernel_time_t msg_ctime;  /* last change time */  
  9.     unsigned long  msg_lcbytes; /* Reuse junk fields for 32 bit */  
  10.     unsigned long  msg_lqbytes; /* ditto */  
  11.     unsigned short msg_cbytes;  /* current number of bytes on queue */  
  12.     unsigned short msg_qnum;    /* number of messages in queue */  
  13.     unsigned short msg_qbytes;  /* max number of bytes on queue */  
  14.     __kernel_ipc_pid_t msg_lspid;   /* pid of last msgsnd */  
  15.     __kernel_ipc_pid_t msg_lrpid;   /* last receive pid */  
  16. };  
可以看到第⼀个 红色条目 就是IPC结构体,即是共有的,后面的都是消息队列所私有的成员。 消息队列是用链表实现的。 


四.消息队列的函数

实现消息队列的相关函数:


  1.生成新消息队列或者取得已存在的消息队列


[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int msgget(ket_t key,int msgflg);  
 key:可以认为是一个端口号,也可以由函数ftok生成。    

            参数: msgflg:              

          IPC_CREAT:如果IPC不存在,则创建一个IPC资源,否则打开操作。                                   

          IPC_EXCL:只有在共享内存不存在的时候,新的共享内存才建立,否则就产生错误。 如果单独使用IPC_CREAT   XXXget()函数要么返回一个已经存在的共享内存的操作符,要 么返回一个新建的共享内存的标识符。 如果将IPC_CREAT和IPC_EXCL标志一起使用,XXXget()将返回一个新建的IPC标识符 ;如果该IPC资源已存在,或者返回-1。      IPC_EXEL标志本身并没有太大的意义,但是和IPC_CREAT标志一起使用可以用来保证所得的对象是新建的,而不是打开已有的对象。 

          返回值:返回msgid。

  2.向队列读/写消息

  msgrcv取消息:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);   

  msgsnd读消息:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);  

     msqid:消息队列的标识码。     

     msgp:指向消息缓冲区的指针,此位置用来暂时存储发送和接收的消息,是一个用户可定义的通用结构,形态如下:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. struct msgstru  
  2. {  
  3.     long mtype;//大于0  
  4.     char mtext[_SIZE_]; //_SIZE_ 用户指定大小  
  5. }  

      msgsz:消息的大小。   

      msgtyp:从消息队列内读取的消息形态。如果值为零,则表示消息队列中的所有消息都会被读取。   

      msgflg:用来指明核心程序在队列没有数据的情况下所应采取的行动。如果msgflg和常数IPC_NOWAIT合用,则在msgsnd()执行时若是消息队列已满,则msgsnd()将不会阻塞,而会立即返回-1,如果执行的是msgrcv(),则在消息队列呈空时,不做等待马上返回-1,并设定 错误码为ENOMSG。当msgflg为0时,msgsnd()及msgrcv()在队列呈满或呈空的情形时,采取 阻塞等待的处理模式。 


.应用

          ———使用消息队列实现一个简单的客户端--服务端的通信

实现代码如下给出:

comm.h

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #pragma once  
  2.   
  3. #include<stdio.h>  
  4. #include<errno.h>  
  5. #include<string.h>  
  6. #include<sys/types.h>  
  7. #include<sys/ipc.h>  
  8. #include<sys/msg.h>  
  9.   
  10. #define _PATH_NAME_ "/tmp"  
  11. #define _PROJ_ID_ 0x6666  
  12. #define _SIZE_ 1024  
  13.   
  14. extern int server_type;  
  15. extern int client_type;  
  16.   
  17.   
  18. struct msgbuf  
  19. {  
  20.     long mtype;  
  21.     char mtext[_SIZE_];  
  22. };  
  23.   
  24. int creat_msg_queue();  
  25. int get_msg_queue();  
  26. //int creat_msg_queue(int msg_id);  
  27. int send_msg(int msg_id,int send_type,const char* msg);  
  28. int recv_msg(int msg_id,int recv_type,char* msg_out);  
  29. int destroy_queue(int msg_id);  

comm.c:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include"comm.h"  
  2.   
  3. int server_type = 1;  
  4. int client_type = 2;  
  5.   
  6.   
  7. static int comm_msg_queue(int flags)  
  8. {  
  9.     key_t _key = ftok(_PATH_NAME_,_PROJ_ID_);  
  10.     if(_key < 0)  
  11.     {  
  12.         printf("%d : %s",errno,strerror(errno));  
  13.         return -1;  
  14.     }  
  15.   
  16.     int msg_id = msgget(_key,flags);  
  17.     //int msg_id = msgget(_key,IPC_CREAT | IPC_EXCL | 0666);  
  18.     return msg_id;  
  19. }  
  20.   
  21. int creat_msg_queue()  
  22. {  
  23.     int flags = IPC_CREAT | IPC_EXCL | 0666;  
  24.     return comm_msg_queue(flags);  
  25. }  
  26.   
  27. int get_msg_queue()  
  28. {  
  29.     int flags = IPC_CREAT;  
  30.     return comm_msg_queue(flags);  
  31. }  
  32.   
  33. int destroy_queue(int msg_id)  
  34. {  
  35.     if(msgctl(msg_id,IPC_RMID,NULL) != 0)  
  36.     {  
  37.         printf("%d : %s",errno,strerror(errno));  
  38.         return -1;  
  39.     }  
  40.   
  41.     return 0;  
  42. }  
  43.   
  44. int send_msg(int msg_id,int send_type,const char* msg)  
  45. {  
  46.     struct msgbuf _buf;  
  47.     _buf.mtype = send_type;  
  48.     strncpy(_buf.mtext,msg,strlen(msg)+1);  
  49.   
  50.     if(msgsnd(msg_id,&_buf,sizeof(_buf.mtext),0) < 0)  
  51.     {  
  52.         printf("%d : %s",errno,strerror(errno));  
  53.         return -1;  
  54.     }  
  55.     return 0;  
  56. }  
  57.   
  58. int recv_msg(int msg_id,int recv_type,char* msg_out)  
  59. {  
  60.     struct msgbuf _buf;  
  61.     _buf.mtype = 0;  
  62.     memset(_buf.mtext,'\0',sizeof(_buf.mtext));  
  63.   
  64.     if(msgrcv(msg_id,&_buf,sizeof(_buf.mtext),recv_type,0) < 0)  
  65.     {  
  66.         printf("%d : %s",errno,strerror(errno));  
  67.         return -1;  
  68.     }  
  69.   
  70.     strcpy(msg_out,_buf.mtext);  
  71.     return 0;  
  72. }  

server.c:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include"comm.h"  
  2.   
  3. int main()  
  4. {  
  5.     int msg_id = creat_msg_queue();  
  6.     if(msg_id <0)  
  7.     {  
  8.         printf("%d : %s\n",errno,strerror(errno));  
  9.         return 1;  
  10.     }  
  11.   
  12.     char buf[_SIZE_];  
  13.     while(1)  
  14.     {  
  15.         memset(buf,'\0',sizeof(buf));  
  16.         recv_msg(msg_id,client_type,buf);  
  17.         printf("client:%s\n",buf);  
  18.         if(strcasecmp(buf,"quit") == 0)  
  19.         {  
  20.             break;  
  21.         }  
  22.   
  23.         printf("client say done,Please Enter# ");  
  24.         fflush(stdout);  
  25.         ssize_t _s = read(0,buf,sizeof(buf)-1);  
  26.         if(_s > 0)  
  27.         {  
  28.             buf[_s - 1] = '\0';  
  29.         }  
  30.   
  31.         send_msg(msg_id,server_type,buf);  
  32.   
  33.     }  
  34.   
  35.     destroy_queue(msg_id);  
  36.     return 0;  
  37. }  

client.c:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include"comm.h"  
  2.   
  3. int main()  
  4. {  
  5.     //int msg_id = creat_msg_queue();  
  6.       
  7.     //if(msg_id <0)  
  8.     //{  
  9.     //  printf("%d : %s\n",errno,strerror(errno));  
  10.     //  return 1;  
  11.     //}  
  12.     //  
  13.     //  
  14.     int msg_id = get_msg_queue();  
  15.   
  16.     char buf[_SIZE_];  
  17.     while(1)  
  18.     {  
  19.         printf("Please Enter:");  
  20.         fflush(stdout);  
  21.         ssize_t _s = read(0,buf,sizeof(buf)-1);  
  22.         if(_s >0 )  
  23.         {  
  24.             buf[_s - 1] = '\0';  
  25.         }  
  26.         send_msg(msg_id,client_type,buf);  
  27.         if(strcasecmp(buf,"quit") == 0)  
  28.         {  
  29.             break;  
  30.         }  
  31.   
  32.         memset(buf,'\0',sizeof(buf));  
  33.         recv_msg(msg_id,server_type,buf);  
  34.         printf("server# %s\n",buf);  
  35.     }  
  36.   
  37.     return 0;  
  38. }  

六.测试过程及结果

头文件:


各个接口:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int creat_msg_queue();  //创建一个消息队列  
  2.   
  3. int get_msg_queue();   //获得消息队列的msg_id  

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int send_msg(int msg_id,int send_type,const char* msg);  //发送消息  

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int recv_msg(int msg_id,int recv_type,char* msg_out);  //接收消息  

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int destroy_queue(int msg_id);  //销毁队列  

server.c:创建消息队列,接收客户端发送的消息,同时给客户端发送消息



client.c:获取msg_id,接收服务端发送的消息,同时给客户端反馈


Makefile:



要生成两个可执行程序,所以使用伪目标all。

$@(依赖关系中代表目标文件) $^(依赖关系中:右边的所有内容)


测试结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值