Linux進程通信 消息隊列

1消息隊列

消息隊列是一個消息鏈表,允許一個或多個進程向它寫消息,另外的進程從中讀取消息,具有FIFO的特性,但是可實現隨即訪問。在內核中,消息隊列由"隊列id"標識。

 

2.使用過程

創建消息隊列==>添加消息==>讀取消息==>刪除隊列

<1>創建消息隊列 msgget()

 

  int msgget(key_t key,int flag);

參數:key  爲IPC_PRIVATE時,建立新的消息隊列

           不爲IPC_PRIVATE,根據flag是否有IPC_CREAT確定

      flag 標誌位

返回:成功,返回消息隊列識別代碼msgid  失敗 返回-1 錯誤信息存放在errno中

<2>向消息隊列添加消息

 

  int msgsnd(int msgid,struct msgbuf *msgp,size_t msgsz,int flag);

參數:msgid  消息隊列id 由msgget()得到

      msgp  存放消息類型和內容

  1. struct msgbuf{ 
  2.  long mtype;/*消息類型*/ 
  3.   char mtext[1];/*消息內容*/ 
  4.  } 

msgbuf在頭文件中未實際定義,需要自己定義。

       msgsz 消息大小

       flag 爲IPC_NOWAIT時,未立即發送,調用進程立即返回

返回:成功,返回消息隊列識別代碼  失敗 返回-1 錯誤信息存放在errno中

<3>從消息隊列讀取消息

  int msgrcv(int msgid,struct msgbuf *msgp,size_t msgsz,long msgty,int flag);

參數: msgid  消息隊列id 由msgget()得到

      msgp  存放消息類型和內容

      msgsz 消息大小

      msgty 消息類型

      flag 爲IPC_NOWAIT時,未立即發送,調用進程立即返回

返回:成功,返回消息隊列識別代碼  失敗 返回-1 錯誤信息存放在errno中

 

<4>控制消息隊列

  int msgctl(int msgid,int cmd,struct msgid_ds, *buf);

參數: msgid  消息隊列id 由msgget()得到

      cmd  IPC_STAT   將消息隊列信息寫入buf

           IPC_SET    根據buf設置爲消息隊列

           IPC_RMID   刪除消息隊列

返回:成功,返回消息隊列識別代碼  失敗 返回-1 錯誤信息存放在errno中

舉例:

1. 子進程向消息隊列發送消息,由父進程讀出

  1. #include<sys/ipc.h> 
  2. #include<sys/msg.h> 
  3. #include<sys/types.h> 
  4. #include<sys/stat.h> 
  5. #include<unistd.h> 
  6. #include<stdio.h> 
  7. #include<string.h> 
  8.  
  9.  
  10. #define KEY 1234 
  11. #define MSGTYPE 4321 
  12. #define SIZE 512 
  13.  
  14. int main() 
  15.    int msgid;/*消息隊列id*/ 
  16.    pid_t pid; 
  17.    struct message  
  18.   { 
  19.    long mtype; 
  20.    char mtext[SIZE]; 
  21.   }msg; 
  22.    
  23.     msgid=msgget(KEY,IPC_CREAT); 
  24.  
  25.    pid=fork(); 
  26.    if(pid<0) 
  27.     { 
  28.      perror("fork error!\n"); 
  29.      exit(0); 
  30.     } 
  31.    if(pid==0) 
  32.   { 
  33.     /*子進程發送消息*/ 
  34.     msg.mtype=MSGTYPE;/*設置消息類型*/ 
  35.     sprintf(msg.mtext,"hello linux!");/*設置消息內容*/ 
  36.     msgsnd(msgid,&msg,SIZE,IPC_NOWAIT);/*發送消息*/ 
  37.     printf("son proc send msg!\n"); 
  38.    exit(0); 
  39.   } 
  40. /*父進程接收消息*/ 
  41.    sleep(2); 
  42.   msgrcv(msgid,&msg,SIZE,MSGTYPE,MSG_NOERROR|IPC_NOWAIT);/*接收消息*/ 
  43.   printf("parent get message:%s\n",msg.mtext,IPC_NOWAIT); 
  44.   msgctl(msgid,IPC_RMID,NULL);/*刪除消息隊列*/ 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章