10-21 使用消息队列实现两个进程的相互通信
1.使用消息队列实现两个进程的相互通信
代码:
#include <myhead.h> #define MSGSZ (sizeof(struct msgbuf)-sizeof(long)) struct msgbuf { long mtype;//消息类型 char mtext[128]; }; //线程主程序 void *task(void*arg) { int msqid=*(int*)arg;//接受主线程的消息队列号 struct msgbuf buf;//定义msgbuf结构体类型 用于收消息 while(1) { msgrcv(msqid,&buf,MSGSZ,2,0);//接收类型为2的消息 printf("收到消息:%s\n",buf.mtext); if(strcmp(buf.mtext,"quit")==0)//输入quit退出通信 { break; } } //删除消息队列 if(msgctl(msqid,IPC_RMID,NULL)==-1) { perror("msgctl error"); return NULL; } pthread_exit(NULL);//子程序退出 } int main(int argc, const char *argv[]) { //创建key key_t key=ftok("/",'k'); if(key==-1) { perror("ftok error"); return -1; } //创建消息队列 int msqid=msgget(key,IPC_CREAT|0664); if(msqid==-1) { perror("msgget error"); return -1; } //创建线程 pthread_t tid=-1; if(pthread_create(&tid,NULL,task,&msqid)!=0) { perror("pthread_cteate error"); return -1; } struct msgbuf buf; printf("开始聊天吧!\n"); while(1) { buf.mtype=1;//输入类型1信息,用于另一个进程的接收端 scanf("%ld",&buf.mtype); fgets(buf.mtext,MSGSZ,stdin);//获取终端输入信息存入结构体 buf.mtext[strlen(buf.mtext)-1]=0;//字符串尾端回车改为'\0' msgsnd(msqid,&buf,MSGSZ,0);//将字符串发送到消息队列 printf("发送成功\n"); if(strcmp(buf.mtext,"quit")==0)//输入quit即退出循环 { break; } } pthread_join(tid,NULL);//回收线程 return 0; }
由于进程2代码和进程1一样就不粘贴上了,只需将进程2的输入信息类型改为2,接收信息类型改为1即可。
执行结果:
2.思维导图: