情境:
進程A向訊息佇列寫訊息,而進程B則從訊息佇列讀訊息。
訊息佇列和之前的管道不同,訊息佇列是相對獨立於進程的,它不需要進程自己來提供同步方法。訊息佇列裡面有訊息就可以讀。
讀取訊息執行個體:msg_rcv.c
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>structmy_msg_st {long int my_msg_type;char some_text[BUFSIZ];};int main(int argc,char **argv){intrunning = 1;intmsgid;structmy_msg_st some_data;long int msg_to_receive = 0;msgid = msgget((key_t)1234,0666 | IPC_CREAT);if(msgid == -1){fprintf(stderr,"Msgget failed!\n");exit(-1);}while(running){if(msgrcv(msgid,(void *)&some_data,BUFSIZ,msg_to_receive,0) == -1){fprintf(stderr,"Msgrcv failed!\n");exit(-1);}printf("You wrote: %s",some_data.some_text);if(strncmp(some_data.some_text,"end",3) == 0){running = 0;}}if(msgctl(msgid,IPC_RMID,0) == -1){fprintf(stderr,"Msgctl failed!\n");exit(-1);}exit(0);}
寫入訊息佇列應用:msg_snd.c
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#defineMAX_TEXT256structmy_msg_st {long int my_msg_type;char some_text[BUFSIZ];};int main(int argc,char **argv){intrunning = 1;intmsgid;structmy_msg_st some_data;charbuffer[BUFSIZ];msgid = msgget((key_t)1234,0666 | IPC_CREAT);if(msgid == -1){fprintf(stderr,"Msgget failed!\n");exit(-1);}while(running){printf("Enter Some Text: ");fgets(buffer,BUFSIZ,stdin);some_data.my_msg_type = 1;strcpy(some_data.some_text,buffer);if(msgsnd(msgid,(void *)&some_data,MAX_TEXT,0) == -1){fprintf(stderr,"Msgsnd failed!\n");exit(-1);}if(strncmp(some_data.some_text,"end",3) == 0){running = 0;}}exit(0);}
注意,這個程式的驗證並不需要兩個進程同時運行。
首先運行snd進程,寫入幾條訊息。
然後啟動rcv進程,讀取訊息並顯示,最後刪除訊息佇列檔案。
備忘:查看系統進程的IPC資源命令
# ipcs //查看ipc資源
# ipcrm //刪除ipc資源