1.使用消息队列完成两个进程间的通信
代码实现:
snd.c发送端:
#include <head.h>
struct mymsg
{
long mtype; //正文类型
char mtext[1024]; //正文内容
};
#define SIZE (sizeof(struct mymsg)-sizeof(long))
int main(int argc, const char *argv[])
{
int pid=fork();
if(pid > 0) //父进程接收消息
{
//1.创建key值
int key=ftok("./",'k');
//2.通过key值创建消息队列
int msgid=msgget(key,IPC_CREAT|0664);
//3.从消息队列中接收消息
struct mymsg info; //定义结构体类型的变量
while(1) //循环接收消息
{
bzero(info.mtext,sizeof(info.mtext));
msgrcv(msgid,&info,SIZE,0,0);
printf("接收到的消息为:%s\n",info.mtext);
if(strcmp(info.mtext,"quit")==0)
break;
}
}
else if(pid == 0) //子进程发送消息
{
//1.创建key值
int key=ftok("./",'j');
//2.通过key值创建消息队列
int msgid=msgget(key,IPC_CREAT|0664);
//3.向消息队列中发送消息
struct mymsg info;
while(1)
{
bzero(info.mtext,sizeof(info.mtext));
printf("请输入您要发送的类型:");
scanf("%ld",&info.mtype);
printf("请输入消息内容:");
scanf("%s",info.mtext);
msgsnd(msgid,info.mtext,SIZE,0);
if(strcmp(info.mtext,"quit")==0)
break;
}
}
else
{
perror("fork error");
return -1;
}
return 0;
}
rcv.c接收端:
#include <head.h>
struct mymsg
{
long mtype; //正文类型
char mtext[1024]; //正文内容
};
#define SIZE (sizeof(struct mymsg)-sizeof(long))
int main(int argc, const char *argv[])
{
int pid=fork();
if(pid > 0) //父进程发送消息
{
//1.创建key值
int key=ftok("./",'j');
//2.通过key值创建消息队列
int msgid=msgget(key,IPC_CREAT|0664);
//3.向消息队列中发送消息
struct mymsg info;
while(1)
{
bzero(info.mtext,sizeof(info.mtext));
printf("请输入您要发送的类型:");
scanf("%ld",&info.mtype);
printf("请输入消息内容:");
scanf("%s",info.mtext);
msgsnd(msgid,info.mtext,SIZE,0);
if(strcmp(info.mtext,"quit")==0)
break;
}
}
else if(pid == 0) //子进程接收消息
{
//1.创建key值
int key=ftok("./",'k');
//2.通过key值创建消息队列
int msgid=msgget(key,IPC_CREAT|0664);
//3.从消息队列中接收消息
struct mymsg info; //定义结构体类型的变量
while(1) //循环接收消息
{
bzero(info.mtext,sizeof(info.mtext));
msgrcv(msgid,&info,SIZE,0,0);
printf("接收到的消息为:%s\n",info.mtext);
if(strcmp(info.mtext,"quit")==0)
break;
}
}
else
{
perror("fork error");
return -1;
}
return 0;
}