作业:使用消息队列完成两个进程间的相互通信
#include <head.h>struct msgbuf
{long mtype; //消息类型char mtext[1024]; //正文大小
};#define SIZE (sizeof(struct msgbuf)-sizeof(long))int main(int argc, const char *argv[])
{//1.创建key值key_t key = ftok("/", 'k');if(key == -1){perror("key create error\n");return -1;}printf("key = %#x\n", key);//2.创建消息队列int msgid = msgget(key, IPC_CREAT|0664);if(msgid == -1){perror("msgget error\n");return -1;}//创建进程pid_t pid = fork();//3.向消息队列中存放数据struct msgbuf buf;if(pid>0){while(1){printf("请输入类型: ");scanf("%ld", &buf.mtype);printf("请输入数据: ");scanf("%s",buf.mtext);//将消息放入消息队列中msgsnd(msgid, &buf, SIZE, 0);//退出if(strcmp(buf.mtext, "quit") == 0){break;}}}else if(pid == 0){while(1){msgrcv(msgid, &buf, SIZE, 1, 0);printf("收到1号消息: %s\n", buf.mtext);if(strcmp(buf.mtext, "quit") == 0){break;}}exit(EXIT_SUCCESS);}else {perror("fork error");return -1;}//4.删除消息队列if(msgctl(msgid, IPC_RMID,NULL) == -1){perror("msgctl error\n");return -1;}wait(NULL);return 0;
}
#include <head.h>struct msgbuf
{long mtype; //消息类型char mtext[1024]; //正文大小
};#define SIZE (sizeof(struct msgbuf)-sizeof(long))int main(int argc, const char *argv[])
{//1.创建key值key_t key = ftok("/", 'k');if(key == -1){perror("key create error\n");return -1;}printf("key = %#x\n", key);//2.创建消息队列int msgid = msgget(key, IPC_CREAT|0664);if(msgid == -1){perror("msgget error\n");return -1;}//创建进程pid_t pid = fork();//3.向消息队列中存放数据struct msgbuf buf;if(pid>0){while(1){printf("请输入类型: ");scanf("%ld", &buf.mtype);printf("请输入数据: ");scanf("%s",buf.mtext);//将消息放入消息队列中msgsnd(msgid, &buf, SIZE, 0);//退出if(strcmp(buf.mtext, "quit") == 0){break;}}}else if(pid == 0){while(1){msgrcv(msgid, &buf, SIZE, 2, 0);printf("收到1号消息: %s\n", buf.mtext);if(strcmp(buf.mtext, "quit") == 0){break;}}exit(EXIT_SUCCESS);}else {perror("fork error");return -1;}wait(NULL);//4.删除消息队列return 0;
}
效果图