使用消息队列去实现2个终端之间的互相聊天
要求:千万不要做出来2个终端之间的消息发送是读一写的,一定要能够做到,一个终端发送n条消息,另一个终端一条消息都不回复
A终端:
#include<myhead.h>
typedef struct msgbuf
{long type;char text[256];
}msg_t;
void* snda(void* arg)
{int id=*(int*)arg;msg_t abuf;int alen=0;while(1){memset(&abuf,0,sizeof(msg_t));abuf.type=1;printf("请输入消息:");scanf("%256s",abuf.text);while(getchar()!=10);alen=strlen(abuf.text);msgsnd(id,&abuf,alen,0);}
}
void* rcvb(void* arg)
{int id=*(int*)arg;msg_t bbuf;int blen=0;while(1){memset(&bbuf,0,sizeof(msg_t));blen=msgrcv(id,&bbuf,256,2,0);printf("B:%s\n",bbuf.text);}}
int main(int argc, char *argv[])
{key_t key=ftok("./talk",1);if(key==-1){perror("ftok");return 1;}int id=msgget(key,IPC_CREAT|0666);pthread_t id2;pthread_t id3;pthread_create(&id2,NULL,snda,&id);pthread_create(&id3,NULL,rcvb,&id);pthread_join(id2,NULL);pthread_join(id3,NULL);return 0;
}
B终端:
#include<myhead.h>
typedef struct msgbuf
{long type;char text[256];
}msg_t;
void* sndb(void* arg)
{int id=*(int*)arg;msg_t bbuf;int blen=0;while(1){memset(&bbuf,0,sizeof(msg_t));bbuf.type=2;printf("请输入消息:");scanf("%256s",bbuf.text);while(getchar()!=10);blen=strlen(bbuf.text);msgsnd(id,&bbuf,blen,0);}
}
void* rcva(void* arg)
{int id=*(int*)arg;msg_t abuf;int alen=0;while(1){memset(&abuf,0,sizeof(msg_t));alen=msgrcv(id,&abuf,256,1,0);printf("A:%s\n",abuf.text);}}
int main(int argc, char *argv[])
{key_t key=ftok("./talk",1);if(key==-1){perror("ftok");return 1;}int id=msgget(key,IPC_CREAT|0666);pthread_t id2;pthread_t id3;pthread_create(&id2,NULL,sndb,&id);pthread_create(&id3,NULL,rcva,&id);pthread_join(id2,NULL);pthread_join(id3,NULL);return 0;
}
效果图: