System V IPC 之 Message Queue
在APUE 14.7節對消息隊列的講解中,最后一段說“我們得出的結論是:在新的應用程式中不應當再使用他們。”
雖然在新的應用程式中不應該再使用消息隊列,我也沒有怎么使用過System V IPC總覺得在UNIX/Linux編程中少了什么,也許學習一下System V IPC對我的自信心會有相當大的幫助,從此我也敢講我知道如何使用IPC了。
先把各個函數原形列出。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflag);
int msgsnd(int msgid, struct msgbuf *msgp, size_t msgsz, int msgflag);
ssize_t msgrcv(int msgid, struct msgbuf *msgp, size_t msgsz, long msgtype, int msgflag);
int msgctl(int msgid, int cmd, struct msqid_ds *buf);
msgget()用來創建Message Queue(服務端)或和一個已建立的Message
Queue連接(客戶端)。key,指定用來生成message
id的關鍵字,msgflag和open()的flags很相似,可用IPC_CREAT, IPC_EXECL, S_IRUSR等。
在服務端,可用IPC_PRIVATE(或0)來指定key值,來生成一個新的Message Queue,或使用指定的key值(32位的無符號數),或使用ftok()來生成一個key。
#include <sys/types.h>
#include <sys/ipc.h>
key_t ftok(const char *pathname, int proj_id);
在客戶端,能夠直接使用服務端生成的message
id(通過某些途徑傳送,如文檔,父子進程),也能夠用msgget通過和服務端使用相同的key值來生成相同的message
id,但不能使用IPC_PRIVATE(或0),msgflag也不能使用IPC_CREAT。
Return Value: Sucess return value is the message id(non-negative integer), otherwise -1 return.
msgsnd()用來發送消息。
struct msgbuf {
long mtype;
char mtext[1];
};
msgsz的計算方法: msgsz = sizeof(msgbuf) - sizeof(long);
msgflag有一個標志:IPC_NOWAIT。當消息隊列已滿(可能是消息總數達到了限制值,也可能是隊列中字節總數達到了限制值),立即出錯返回,假如沒有指定,則阻塞。
msgrcv()用來接收消息。msgtype用來指定讀取的消息類型。msgtype == 0, 返回第一個消息; msgtype >
0, 返回消息類型為msgtype的消息;msgtype < 0, 返回隊列中類型值小于msgtype的絕對值的消息集中最小的消息。
msgflag有兩個值:MSG_NOERROR, IPC_NOWAIT。當MSG_NOERROR被指定的時候,若消息太長就被截斷,否則返回錯誤;IPC_NOWAIT用于需要讀取的消息不存在時則阻塞。
msgctl用于控制消息隊列。cmd有三種值:IPC_STAT,IPC_SET,IPC_RMID。
IPC_STAT用于取出消息隊列的 msqid_ds結構并保存到buf中。
IPC_SET用來把buf指向的msqid_ds,配置成消息隊列的msqid_ds。只有四個值能夠更改:msg_perm.uid, msg_perm.gid,msg_perm.mode, msg_qbytes。
IPC_RMID用來刪除消息隊列。
struct msqid_ds
{
struct ipc_perm msg_perm;
ulong msg_qbytes; //max of bytes of queue
...
};
struct ipc_perm
{
uid_t uid; //owner's effective user id
gid_t gid; //owner's effective group id
uid_t cuid; //creator's effective user id
gid_t cgid; //creator's effective group id
mode_t mode; //access modes
ulong seq; //slot usage sequence number
key_t key;
};
posted on 2008-10-09 09:03 茶 閱讀(1007) 評論(0) 編輯 收藏 引用 所屬分類: liunx編程技術