使用消息隊列完成兩個進程之間相互通信
代碼
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.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");return -1;}//此時key已經創建出來printf("key = %#x\n", key);//2、創建消息隊列int msgid = msgget(key, IPC_CREAT|0664);if(msgid == -1){perror("msgget error");return -1;}printf("msgid = %d\n", msgid); //輸出消息隊列id號struct msgbuf buf;//需要創建兩個進程,父進程從管道1中讀數據,子進程向管道2中寫數據pid_t pid = -1;pid = fork();if(pid < 0){perror("fork error");return -1;}else 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{//父進程負責向消息隊列中讀數據//3、向消息隊列中存放數據while(1){//將消息從消息隊列中讀取出來msgrcv(msgid, &buf, SIZE, 10, 0);//參數1:消息隊列id//參數2:容器起始地址//參數3:消息正文大小//參數4:要讀取的消息類型//參數5:是否阻塞//將讀取的消息打印出來printf("收到消息:%s\n", buf.mtext);}}//4、刪除消息隊列if(msgctl(msgid, IPC_RMID, NULL) == -1){perror("msgctl error");return -1;}return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.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");return -1;}//此時key已經創建出來printf("key = %#x\n", key);//2、創建消息隊列int msgid = msgget(key, IPC_CREAT|0664);if(msgid == -1){perror("msgget error");return -1;}printf("msgid = %d\n", msgid); //輸出消息隊列id號struct msgbuf buf;//需要創建兩個進程,父進程從管道1中讀數據,子進程向管道2中寫數據pid_t pid = -1;pid = fork();if(pid < 0){perror("fork error");return -1;}else if(pid == 0){//子進程負責向中讀數據while(1){//將消息從消息隊列中讀取出來msgrcv(msgid, &buf, SIZE, 9,0);//參數1:消息隊列id//參數2:容器起始地址//參數3:消息正文大小//參數4:要讀取的消息類型//參數5:是否阻塞//將讀取的消息打印出來printf("收到消息:%s\n", buf.mtext);}}else{//父進程負責向消息隊列中寫數據//3、向消息隊列中存放數據while(1){//輸入消息內容printf("請輸入您要發送的類型:");scanf("%ld", &buf.mtype);printf("請輸入消息內容:");scanf("%s", buf.mtext);//將消息放入消息隊列中msgsnd(msgid, &buf, SIZE, 0);//判斷退出條件if(strcmp(buf.mtext, "quit") == 0){break;}}}//4、刪除消息隊列if(msgctl(msgid, IPC_RMID, NULL) == -1){perror("msgctl error");return -1;}return 0;
}
運行效果:
思維導圖