消息队列实现两个进程数据交互

//segqueue_r.c 先接收数据再发送数据
 #include<stdio.h>
 #include<unistd.h>
 #include<stdlib.h>
 #include<string.h>
 #include<errno.h>
 #include<sys/msg.h>
 #include<sys/ipc.h>

 #define IPC_KEY 0x123123
  //定义消息队列的key,好知道写道那个队列中,取哪个队列中拿
  #define TYPE_R 1
  #define TYPE_W 2
  //我们赋值传输的数据库类型

  struct msgbuf
  {
      long mtype;
      int crc;
      char mtext[1024];
  }readbuf, sendbuf;


  int main()
  {
      int msqid = -1;
 //创建消息队列,若存在则打开,不存在则创建
      msqid = msgget(IPC_KEY,IPC_CREAT|0664);
      if(msqid < 0)
      {
          perror("msgget error");
          return -1;
      }
      while(1)
      {
        //   struct msgbuf readbuf, sendbuf;
          //接收数据
          msgrcv(msqid, &readbuf, sizeof(readbuf), TYPE_W, 0);
          printf("Recieved %d bytes of data from A, Checked correctly, Notify A that %d bytes of data have been recieved and checked correctly\n",strlen(readbuf.mtext), strlen(readbuf.mtext));

          //发送数据
          sendbuf.mtype = TYPE_R;
          sendbuf.crc = 1;
          printf(">>>");
        //   scanf("%s",sendbuf.mtext);
          msgsnd(msqid, &sendbuf, sizeof(sendbuf),0);
      }
      msgctl(msqid,IPC_RMID,NULL);
      return 0;
  }
//segqueue_w.c 先发送数据再接收数据
 #include<stdio.h>
 #include<unistd.h>
 #include<stdlib.h>
 #include<string.h>
 #include<errno.h>
 #include<sys/msg.h>
 #include<sys/ipc.h>

 #define IPC_KEY 0x123123
  //定义消息队列的key,好知道写道那个队列中,取哪个队列中拿
  #define TYPE_R 1
  #define TYPE_W 2
  //我们赋值传输的数据库类型

  struct msgbuf
  {
      long mtype;
      int crc;
      char mtext[1024];
  }readbuf, sendbuf;



  int main()
  {
      int msqid = -1;
 //创建消息队列,若存在则打开,不存在则创建
      msqid = msgget(IPC_KEY,IPC_CREAT|0664);
      if(msqid < 0)
      {
          perror("msgget error");
          return -1;
      }
      while(1)
      {
          //发送数据
          sendbuf.mtype = TYPE_W;
          printf(">>>");
          gets(sendbuf.mtext);
          sendbuf.crc = 
          printf("A sent %d bytes of data to B", strlen(sendbuf.mtext));
          msgsnd(msqid,&sendbuf,sizeof(sendbuf),0);
          //接收数据
          msgrcv(msqid,&readbuf,sizeof(readbuf),TYPE_R,0);
          printf("r say:[%d]\n",readbuf.crc);
      }
      msgctl(msqid,IPC_RMID,NULL);
      return 0;
  }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值