1.使用消息队列完成两个进程之间的通信
程序A代码:
#include <myhead.h>
struct msgbuf
{long mtype;char mtext[1024];
};
//定义一个宏,表示消息正文内容的大小
#define MSGSIZE sizeof(struct msgbuf)-sizeof(long)int main(int argc, const char *argv[])
{//创建一个key值key_t key;key=ftok("/",'k');if(key==-1){perror("ftok error");return -1;}printf("ftok success key=%d\n",key);//通过key值创建消息队列int msqid=-1;if((msqid=msgget(key,IPC_CREAT|0664))==-1){perror("msgget error");return -1;}printf("msgget success msqid=%d\n",msqid);//创建父子进程pid_t pid;pid=fork();if(pid>0){//父进程,向消息队列中放入类型1的数据struct msgbuf buf;buf.mtype=1;while(1){bzero(buf.mtext,sizeof(buf.mtext));printf("请输入内容:");fgets(buf.mtext,sizeof(buf.mtext),stdin);buf.mtext[strlen(buf.mtext)-1]=0;//将消息放入队列中msgsnd(msqid,&buf,MSGSIZE,0);printf("发送成功\n");if(strcmp(buf.mtext,"quit")==0){break;}}}else if(pid==0){//子进程,从消息队列中读取类型为2的数据struct msgbuf rbuf;while(1){bzero(rbuf.mtext,sizeof(rbuf.mtext));//从消息队列中读取一个消息msgrcv(msqid,&rbuf,MSGSIZE,2,0);printf("收到的消息为:%s\n",rbuf.mtext);if(strcmp(rbuf.mtext,"quit")==0){break;}}}else{perror("fork error");return -1;}return 0;
}
程序B代码:
#include <myhead.h>
struct msgbuf
{long mtype;char mtext[1024];
};
//定义一个宏,表示消息正文内容的大小
#define MSGSIZE sizeof(struct msgbuf)-sizeof(long)int main(int argc, const char *argv[])
{//创建一个key值key_t key;key=ftok("/",'k');if(key==-1){perror("ftok error");return -1;}printf("ftok success key=%d\n",key);//通过key值创建消息队列int msqid=-1;if((msqid=msgget(key,IPC_CREAT|0664))==-1){perror("msgget error");return -1;}printf("msgget success msqid=%d\n",msqid);//创建父子进程pid_t pid;pid=fork();if(pid>0){//父进程,向消息队列中读取类型1的数据struct msgbuf buf;buf.mtype=1;struct msgbuf rbuf;while(1){bzero(rbuf.mtext,sizeof(rbuf.mtext));//从消息队列中读取一个消息msgrcv(msqid,&rbuf,MSGSIZE,1,0);printf("收到的消息为:%s\n",rbuf.mtext);if(strcmp(rbuf.mtext,"quit")==0){break;}}}else if(pid==0){//子进程,向消息队列中写入类型为2的数据struct msgbuf wbuf;wbuf.mtype=2;while(1){bzero(wbuf.mtext,sizeof(wbuf.mtext));printf("请输入内容:");fgets(wbuf.mtext,sizeof(wbuf.mtext),stdin);wbuf.mtext[strlen(wbuf.mtext)]=0;//将消息放入队列中msgsnd(msqid,&wbuf,MSGSIZE,0);printf("发送成功\n");if(strcmp(wbuf.mtext,"quit")==0){break;}}}else{perror("fork error");return -1;}return 0;
}
运行结果: