消息队列通讯

1.阻塞方式 get 数据

int msg_fd=0;
int ret=0;

typedef struct PipeMsg{

    long int type ;  // 消息中的数据为结构体,必须有 long int type 
    unsigned char rcvbuf[100];
 }t_PipeMsg;


void main()
{
  t_PipeMsg gt_PipeMsg ;

  msg_fd = msgget(1000,0666|IPC_CREAT);
  if(msg_fd<0)
   {
       printf("create 1000 msg fail\n");
   }

    while(1)
    {
         ret= msgrcv(msg_fd,&gt_PipeMsg.rcvbuf[0],100,0,0); //注意收到的数据,不是放在&gt_PipeMsg
         if(ret>0)
        {
            int i=0;
            printf("Rcv %d \r\n",ret);
            for(i=0;i<ret;i++)
            {
                 printf("%x,",gt_PipeMsg.rcvbuf[i]);
            }
            printf("\r\n");

        }
         else if(ret <0 )
         {
          printf("fail \n,err is %d",ret);
         }
    }
}

2.发送数据线程
// 注意 管道中的数据 必须有个 long int 的type

typedef struct PipeMsg{
    long int  type ; // 消息中的数据为结构体,必须有 long int type 
    unsigned char rcvbuf[100];
 }t_PipeMsg;
int msg_fd=0;
int ret=0;
int send_count=0;


void main(int argc ,char *argv[])
{
   t_PipeMsg   gt_PipeMsg ;
   gt_PipeMsg.type =0 ;
   int i=0;
   for(i=0;i<10;i++)
    {
    gt_PipeMsg.rcvbuf[i] =i;
    }
   // 创建管道
     msg_fd = msgget(1000,0666|IPC_CREAT);
     if(msg_fd<0)
      {
         printf("create 1000 msg fail\n");
      }
    while(1) //注意发送的不是这个结构体而是后面的数据     结构体后面的长度, 是buf 的长度
        {
        if( msgsnd(msg_fd,  &gt_PipeMsg.rcvbuf[0], 13  ,IPC_NOWAIT) !=0)//注意发送的数据不是结构体的长度,而是结构体中要发送的数据的长度
       {
            printf("pipe msg snd fail \r\n");
       }
        sleep(5);

     }

猜你喜欢

转载自blog.csdn.net/tiger15605353603/article/details/81351746