1> 使用消息队列完成两个进程之间相互通信
#include <myhead.h>
#define SIZE sizeof(struct msgbuf)-sizeof(long)
//要发送的消息类型
struct msgbuf
{
long mtype;
char mtext[1024];
};
//定义分支线程函数
void *task(void *arg)
{
//分支线程,实现从消息队列中接收类型为2的数据
int msqid = *(int *)arg;
struct msgbuf rbuf;
while(1)
{
msgrcv(msqid, &rbuf, SIZE, 2, 0);
if(strcmp(rbuf.mtext, "quit") == 0)
{
break;
}
printf("B:%s\n", rbuf.mtext);
}
//退出线程
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
//创建key值
key_t key = ftok("/", 'C');
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) == -1)
{
printf("pthread_create error\n");
return -1;
}
//主线程,实现向消息队列中发送类型为1的数据
struct msgbuf wbuf;
while(1)
{
wbuf.mtype = 1; //设置发送过去的消息类型为1
printf("请输入>>>");
fgets(wbuf.mtext, SIZE, stdin);
wbuf.mtext[strlen(wbuf.mtext)-1] = 0;
msgsnd(msqid, &wbuf, SIZE, 0);
if(strcmp(wbuf.mtext, "quit") == 0)
{
break;
}
}
//回收线程资源
pthread_join(tid, NULL);
return 0;
}
#include <myhead.h>
#define SIZE sizeof(struct msgbuf)-sizeof(long)
//要发送的消息类型
struct msgbuf
{
long mtype;
char mtext[1024];
};
//定义分支线程函数
void *task(void *arg)
{
//分支线程,实现从消息队列中接收类型为1的数据
int msqid = *(int *)arg;
struct msgbuf rbuf;
while(1)
{
msgrcv(msqid, &rbuf, SIZE, 1, 0);
if(strcmp(rbuf.mtext, "quit") == 0)
{
break;
}
printf("A:%s\n", rbuf.mtext);
}
//退出线程
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
//创建key值
key_t key = ftok("/", 'C');
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) == -1)
{
printf("pthread_create error\n");
return -1;
}
//主线程,实现向消息队列中发送类型为2的数据
struct msgbuf wbuf;
while(1)
{
wbuf.mtype = 2; //设置发送过去的消息类型为2
printf("请输入>>>");
fgets(wbuf.mtext, SIZE, stdin);
wbuf.mtext[strlen(wbuf.mtext)-1] = 0;
msgsnd(msqid, &wbuf, SIZE, 0);
if(strcmp(wbuf.mtext, "quit") == 0)
{
break;
}
}
//回收线程资源
pthread_join(tid, NULL);
return 0;
}
思维导图: