Linux訊息佇列
阿新 • • 發佈:2021-10-27
訊息佇列函式(msgget、msgctl、msgsnd、msgrcv)及其範例
傳送端
點選檢視程式碼
/********************************************************** * Copyright (C) 2021 Dcs Ind. All rights reserved. * * Author : yunfei.cao * Email : **********@outlook.com * Create time : 2021-10-27 21:08 * Last modified : 2021-10-27 21:08 * Filename : msg_send.c * Description : * *******************************************************/ #include<stdlib.h> #include<string.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<linux/msg.h> #include<stdio.h> #define MAXMSG 512 struct my_msg //訊息佇列結構體 { long int my_msg_type; int i; char some_text[MAXMSG]; }msg; main() { int msgid; char buffer[BUFSIZ]; msgid=msgget(12,0666|IPC_CREAT); //建立訊息佇列 while(1){ puts("Enter some text:"); fgets(buffer,BUFSIZ,stdin); msg.i++; printf("i=%d\n",msg.i); msg.my_msg_type=3; strcpy(msg.some_text,buffer); msgsnd(msgid,&msg,MAXMSG,0); //傳送資料到緩衝區 if(strncmp(msg.some_text,"end",3)==0){ //比較輸入,若為end則跳出迴圈 break; } } exit(0); }
接收端
點選檢視程式碼
/********************************************************** * Copyright (C) 2021 Dcs Ind. All rights reserved. * * Author : yunfei.cao * Email : **********@outlook.com * Create time : 2021-10-27 21:09 * Last modified : 2021-10-27 21:09 * Filename : msg_receive.c * Description : * *******************************************************/ #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/types.h> #include<linux/msg.h> #include<stdio.h> #define MAXMSG 512 struct my_msg { long int my_msg_type; int i; char some_text[MAXMSG]; }msg; main() { int msgid; msg.my_msg_type=3; msgid=msgget(12,0666|IPC_CREAT); while(1) { msgrcv(msgid,&msg,BUFSIZ,msg.my_msg_type,0); printf("You wrote:%s and i=%d\n",msg.some_text,msg.i); if(strncmp(msg.some_text,"end",3)==0) break; } msgctl(msgid,IPC_RMID,0); exit(0); }