任务:
利用进程A(父子进程)和进程B(父子进程),使用消息队列实现自由通信。
思路:
进程A ----> 进程B 发送消息fgets或者scanf() 消息的编号 1
进程B ----> 进程A 发送消息的fgets或scanf() 信号的编号 2
//先写进程A的代码实现
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
struct msgbuf
{
long mtype; //--->消息的类型---指的就是消息编号 1
char mtext[20]; //---->消息的数据
};
int main(int argc, char *argv[])
{
key_t key;
int id,ret;
int msgid;
struct msgbuf r_msg = {0};
struct msgbuf t_msg = {0};
//调用ftok函数
key=ftok("./2.txt",1);
printf("key = %d\r\n",key);
//利用msgget函数,获取消息队列的ID
msgid = msgget(key,IPC_CREAT|0644);
//利用printf将对应的msgid输出一下
printf("msgid = %d\r\n",msgid);
//利用fork函数,创建一个子进程
ret = fork(); //创建子进程
if(ret ==0)
{
while(1)
{
//子进程完成的事情
msgrcv(msgid,&r_msg,sizeof(r_msg),1,0);
printf("recv buf = %s\r\n",r_msg.mtext);
}
}
else
{
while(1)
{
//父进程完成的事情
scanf("%s",t_msg.mtext);
//给对应的消息队列添加编号
t_msg.mtype = 2;
//调用一下msgsnd函数
msgsnd(msgid,&t_msg, sizeof(t_msg), 0);
}
}
exit(0);
}
//写进程B的代码实现
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
struct msgbuf
{
long mtype; //--->消息的类型---指的就是消息编号 1
char mtext[20]; //---->消息的数据
};
int main(int argc, char *argv[])
{
key_t key;
int id,ret;
int msgid;
struct msgbuf r_msg = {0};
struct msgbuf t_msg = {0};
//调用ftok函数
key=ftok("./2.txt",1);
printf("key = %d\r\n",key);
//利用msgget函数,获取消息队列的ID
msgid = msgget(key,IPC_CREAT|0644);
//利用printf将对应的msgid输出一下
printf("msgid = %d\r\n",msgid);
//利用fork函数,创建一个子进程
ret = fork(); //创建子进程
if(ret ==0)
{
while(1)
{
//子进程完成的事情
msgrcv(msgid,&r_msg,sizeof(r_msg),2,0);
printf("recv buf = %s\r\n",r_msg.mtext);
}
}else
{
while(1)
{
//父进程完成的事情
scanf("%s",t_msg.mtext);
//给对应的消息队列添加编号
t_msg.mtype = 1;
//调用一下msgsnd函数
msgsnd(msgid,&t_msg, sizeof(t_msg), 0);
}
}
exit(0);
}