//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>#defineIPC_KEY0x123123//定义消息队列的key,好知道写道那个队列中,取哪个队列中拿#defineTYPE_R1#defineTYPE_W2//我们赋值传输的数据库类型structmsgbuf{long mtype;int crc;char mtext[1024];}readbuf, sendbuf;intmain(){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);return0;}
//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>#defineIPC_KEY0x123123//定义消息队列的key,好知道写道那个队列中,取哪个队列中拿#defineTYPE_R1#defineTYPE_W2//我们赋值传输的数据库类型structmsgbuf{long mtype;int crc;char mtext[1024];}readbuf, sendbuf;intmain(){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);return0;}