一、思维导图
二、习题
#define MSGSIZE sizeof(struct msgbuf)-sizeof(long)
int main(int argc, const char *argv[])
{//创建子进程pid_t pid=fork();//在父进程实现读功能if(pid>0){//1、创建key值key_t key = 0;if((key=ftok("/", 'k')) == -1){perror("ftok error");return -1;}//2、根据key值创建一个消息队列int msqid = -1;if((msqid = msgget(key, IPC_CREAT|0664)) == -1){perror("msgget error");return -1;}//定义一个消息struct msgbuf rbuf;while(1){//清空容器bzero(rbuf.mtext, sizeof(rbuf.mtext));msgrcv(msqid, &rbuf, MSGSIZE, 2, 0); //只接收类型为2printf("收到消息为:%s\n", rbuf.mtext);if(strcmp(rbuf.mtext, "quit")==0){break;}}//将消息队列删除if(msgctl(msqid, IPC_RMID, NULL) !=0){perror("msgctl error");return -1;}}//在子进程实现写功能if(pid==0){//1、创建key值key_t key = 0;if((key=ftok("/", 'k')) == -1){perror("ftok error");return -1;}//2、根据key值创建一个消息队列int msqid = -1;if((msqid = msgget(key, IPC_CREAT|0664)) == -1){perror("msgget error");return -1;}//定义一个消息struct msgbuf sbuf;while(1){//清空正文的容器bzero(sbuf.mtext, sizeof(sbuf.mtext));sbuf.mtype=1;printf("请输入消息正文:");fgets(sbuf.mtext, sizeof(sbuf.mtext), stdin);sbuf.mtext[strlen(sbuf.mtext)-1] = 0;//将消息存放入队列中msgsnd(msqid, &sbuf, MSGSIZE, 0);printf("发送成功\n");if(strcmp(sbuf.mtext, "quit")==0){break;}}
}return 0;
}
#define MSGSIZE sizeof(struct msgbuf)-sizeof(long)
int main(int argc, const char *argv[])
{//创建子进程pid_t pid=fork();//在父进程实现读功能if(pid>0){//1、创建key值key_t key = 0;if((key=ftok("/", 'k')) == -1){perror("ftok error");return -1;}//2、根据key值创建一个消息队列int msqid = -1;if((msqid = msgget(key, IPC_CREAT|0664)) == -1){perror("msgget error");return -1;}//定义一个消息struct msgbuf rbuf;while(1){//清空容器bzero(rbuf.mtext, sizeof(rbuf.mtext));msgrcv(msqid, &rbuf, MSGSIZE, 1, 0); //只接收类型为1printf("收到消息为:%s\n", rbuf.mtext);if(strcmp(rbuf.mtext, "quit")==0){break;}}//将消息队列删除if(msgctl(msqid, IPC_RMID, NULL) !=0){perror("msgctl error");return -1;}}//在子进程实现写功能if(pid==0){//1、创建key值key_t key = 0;if((key=ftok("/", 'k')) == -1){perror("ftok error");return -1;}//2、根据key值创建一个消息队列int msqid = -1;if((msqid = msgget(key, IPC_CREAT|0664)) == -1){perror("msgget error");return -1;}//定义一个消息struct msgbuf sbuf;while(1){//清空正文的容器bzero(sbuf.mtext, sizeof(sbuf.mtext));sbuf.mtype=2;printf("请输入消息正文:");fgets(sbuf.mtext, sizeof(sbuf.mtext), stdin);sbuf.mtext[strlen(sbuf.mtext)-1] = 0;//将消息存放入队列中msgsnd(msqid, &sbuf, MSGSIZE, 0);printf("发送成功\n");if(strcmp(sbuf.mtext, "quit")==0){break;}}
}return 0;
}