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 存放消息類型和內容
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. 子進程向消息隊列發送消息,由父進程讀出
- #include<sys/ipc.h>
- #include<sys/msg.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<unistd.h>
- #include<stdio.h>
- #include<string.h>
- #define KEY 1234
- #define MSGTYPE 4321
- #define SIZE 512
- int main()
- {
- int msgid;/*消息隊列id*/
- pid_t pid;
- struct message
- {
- long mtype;
- char mtext[SIZE];
- }msg;
- msgid=msgget(KEY,IPC_CREAT);
- pid=fork();
- if(pid<0)
- {
- perror("fork error!\n");
- exit(0);
- }
- if(pid==0)
- {
- /*子進程發送消息*/
- msg.mtype=MSGTYPE;/*設置消息類型*/
- sprintf(msg.mtext,"hello linux!");/*設置消息內容*/
- msgsnd(msgid,&msg,SIZE,IPC_NOWAIT);/*發送消息*/
- printf("son proc send msg!\n");
- exit(0);
- }
- /*父進程接收消息*/
- sleep(2);
- msgrcv(msgid,&msg,SIZE,MSGTYPE,MSG_NOERROR|IPC_NOWAIT);/*接收消息*/
- printf("parent get message:%s\n",msg.mtext,IPC_NOWAIT);
- msgctl(msgid,IPC_RMID,NULL);/*刪除消息隊列*/
- }