使用消息队列实现两个进程的相互通信
进程1:
#include <myhead.h>
//定义消息结构体
typedef struct
{
long mtype; //消息类型
char mtext[1024]; //消息正文
}msgbuf;
#define MSGSZ (sizeof(msgbuf) - sizeof(long))
int main(int argc, const char *argv[])
{
//创建key值
key_t key = ftok("./",'0');
if(key == -1)
{
perror("ftok error");
return -1;
}
//创建消息队列
int msgid = msgget(key,IPC_CREAT|06);
if( msgid == -1 )
{
perror("msgget error");
return -1;
}
//创建2个进程
pid_t pid = fork();
msgbuf sbuf,rbuf;
//当前进程用于发送消息
if(pid > 0)
{
while(1)
{
//printf("发送消息的类型>>>");
//scanf("%ld",&sbuf.mtype);
//getchar(); //吸收回车
sbuf.mtype = 1; //本进程发送消息的类型为1
//printf("%ld\n",sbuf.mtype);
//printf("发送消息的正文>>>");
fgets(sbuf.mtext , MSGSZ , stdin);
sbuf.mtext[strlen(sbuf.mtext) - 1] = '\0'; //将回车置为0
msgsnd(msgid , &sbuf ,MSGSZ , 0); //发送消息的正文
//printf("发送成功\n");
if( strcmp(sbuf.mtext,"quit") == 0 ) //结束循环
{
break;
}
}
}
//子进程用于接收消息
else if(pid == 0)
{
while(1)
{
rbuf.mtype = 2; //本进程接收消息的类型
msgrcv(msgid , &rbuf , MSGSZ , rbuf.mtype ,0); //接收信息
printf("张三:%s\n",rbuf.mtext);
if(strcmp(rbuf.mtext,"quit") == 0) //结束循环
{
break;
}
}
//删除消息队列
if( msgctl(msgid,IPC_RMID,NULL) == -1)
{
perror("msgctl error");
return -1;
}
exit(EXIT_SUCCESS); //退出进程
}
else
{
perror("fork error");
return -1;
}
wait(NULL); //回收子进程资源
return 0;
}
进程2:
#include <myhead.h>
//定义消息结构体
typedef struct
{
long mtype; //消息类型
char mtext[1024]; //消息正文
}msgbuf;
#define MSGSZ (sizeof(msgbuf) - sizeof(long))
int main(int argc, const char *argv[])
{
//创建key值
key_t key = ftok("./",'0');
if(key == -1)
{
perror("ftok error");
return -1;
}
//创建消息队列
int msgid = msgget(key,IPC_CREAT|06);
if( msgid == -1 )
{
perror("msgget error");
return -1;
}
//创建2个进程
pid_t pid = fork();
msgbuf sbuf,rbuf;
//当前进程用于发送消息
if(pid > 0)
{
while(1)
{
//printf("发送消息的类型>>>");
//scanf("%ld",&sbuf.mtype);
//getchar(); //吸收回车
sbuf.mtype = 2; //本进程发送的消息类型
//printf("%ld\n",sbuf.mtype);
//printf("发送消息的正文>>>");
fgets(sbuf.mtext , MSGSZ , stdin);
sbuf.mtext[strlen(sbuf.mtext) - 1] = '\0'; //将回车置为0
msgsnd(msgid , &sbuf ,MSGSZ , 0); //发送消息的正文
//printf("发送成功\n");
if( strcmp(sbuf.mtext,"quit") == 0 ) //结束循环
{
break;
}
}
}
//子进程用于接收消息
else if(pid == 0)
{
while(1)
{
rbuf.mtype = 1;
msgrcv(msgid , &rbuf , MSGSZ , rbuf.mtype ,0); //接收信息
printf("李四:%s\n",rbuf.mtext);
if(strcmp(rbuf.mtext,"quit") == 0) //结束循环
{
break;
}
}
exit(EXIT_SUCCESS); //退出进程
}
else
{
perror("fork error");
return -1;
}
wait(NULL); //回收进程资源
return 0;
}
思维导图: