用消息队列实现AB进程对话,要求AB进程能够随时收发。
A进程
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <signal.h>
#define MSG_EXCEPT 02000
struct msgbuf
{
long mtype; //消息类型,必须大于0
char mtext[128]; //消息内容,根据需求改变
};
int main(int argc, const char *argv[])
{
//创建key值
key_t key=ftok("/home/ubuntu/",1);
if(key<0)
{
perror("ftok");
return -1;
}
//创建消息队列,获取消息队列的msqid
int msqid=msgget(key,IPC_CREAT|0664);
if(msqid<0)
{
perror("msgget");
return -1;
}
//发送数据
struct msgbuf snd;
ssize_t res=0;
pid_t cpid=fork();
if(cpid>0)
{
while(1)
{
printf("请输入消息类型>>>>");
scanf("%ld",&snd.mtype);
while(getchar()!=10);
if(0==snd.mtype)
break;
printf("请输入消息内容>>>>");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1] = '\0';
//阻塞方式发送,当消息队列满了,该函数阻塞
if(msgsnd(msqid,&snd,sizeof(snd.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
printf("msgsnd success\n");
if(strcmp(snd.mtext,"quit")==0)
{
kill(cpid,9);
exit(1);
}
}
}
else if(cpid==0)
{
while(1)
{
//阻塞形式,读取消息队列中第一条消息
msgrcv(msqid,&snd,sizeof(snd.mtext),1,0);
if(strcmp(snd.mtext,"quit")==0)
{
kill(cpid,9);
exit(1);
}
printf("mtype=%ld mtext=%s\n",snd.mtype,snd.mtext);
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
B进程
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <signal.h>
#define MSG_EXCEPT 02000
struct msgbuf
{
long mtype; //消息类型,必须大于0
char mtext[128]; //消息内容,根据需求改变
};
int main(int argc, const char *argv[])
{
//创建key值
key_t key=ftok("/home/ubuntu/",1);
if(key<0)
{
perror("ftok");
return -1;
}
//创建消息队列,获取消息队列的msqid
int msqid=msgget(key,IPC_CREAT|0664);
if(msqid<0)
{
perror("msgget");
return -1;
}
//发送数据
struct msgbuf snd;
ssize_t res=0;
pid_t cpid=fork();
if(cpid>0)
{
while(1)
{
printf("请输入消息类型>>>>");
scanf("%ld",&snd.mtype);
while(getchar()!=10);
if(0==snd.mtype)
break;
printf("请输入消息内容>>>>");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1] = '\0';
//阻塞方式发送,当消息队列满了,该函数阻塞
if(msgsnd(msqid,&snd,sizeof(snd.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
printf("msgsnd success\n");
if(strcmp(snd.mtext,"quit")==0)
{
kill(cpid,9);
exit(1);
}
}
}
else if(cpid==0)
{
while(1)
{
//阻塞形式,读取消息队列中第一条消息
msgrcv(msqid,&snd,sizeof(snd.mtext),2,0);
if(strcmp(snd.mtext,"quit")==0)
{
kill(cpid,9);
exit(1);
}
printf("mtype=%ld mtext=%s\n",snd.mtype,snd.mtext);
}
}
else
{
perror("fork");
return -1;
}
return 0;
}