Linux IPC实践(6) --System V消息队列(3)
消息隊(duì)列綜合案例
消息隊(duì)列實(shí)現(xiàn)回射客戶/服務(wù)器
?server進(jìn)程接收時(shí),?指定msgtyp為0,?從隊(duì)首不斷接收消息
server進(jìn)程發(fā)送時(shí),?將mtype指定為接收到的client進(jìn)程的pid
?
client進(jìn)程發(fā)送的時(shí)候,?mtype指定為自己進(jìn)程的pid
client進(jìn)程接收時(shí),?需要將msgtyp指定為自己進(jìn)程的pid,?只接收消息類型為自己pid的消息;
// client/server進(jìn)程接收/發(fā)送的數(shù)據(jù)結(jié)構(gòu) const int MSGMAX = 8192; struct msgBuf {long mtype; //保存客戶進(jìn)程的pid(需要將pid強(qiáng)制轉(zhuǎn)換成為long)char mtext[MSGMAX]; //保存客戶進(jìn)程真實(shí)發(fā)送的數(shù)據(jù) }; //server.cpp void echoServer(int msgid) {struct msgBuf buf;int nrcv;while (true){bzero(&buf, sizeof(buf));if ((nrcv = msgrcv(msgid, &buf, sizeof(buf.mtext), 0, 0)) == -1)err_exit("msgrcv error");cout << "recv: " << buf.mtext;if (msgsnd(msgid, &buf, strlen(buf.mtext), 0) == -1)err_exit("msgsnd error");} }int main() {key_t key = ftok("/tmp/echoSeed", 0x1234);int msgid = msgget(key, IPC_CREAT|0666);if (msgid == -1)err_exit("msgget error");echoServer(msgid); } //client.cpp void echoServer(int msgid) {struct msgBuf buf;int nrcv;while (true){bzero(&buf, sizeof(buf));if ((nrcv = msgrcv(msgid, &buf, sizeof(buf.mtext), 0, 0)) == -1)err_exit("msgrcv error");cout << "recv: " << buf.mtext;if (msgsnd(msgid, &buf, strlen(buf.mtext), 0) == -1)err_exit("msgsnd error");} }int main() {key_t key = ftok("/tmp/echoSeed", 0x1234);int msgid = msgget(key, IPC_CREAT|0666);if (msgid == -1)err_exit("msgget error");echoServer(msgid); }附-ftok用法
#include <sys/types.h> #include <sys/ipc.h> key_t ftok(const char *pathname, int proj_id);描述信息:
? ?The?ftok()?function?uses?the?identity(象征)?of?the?file?named?by?the?given?pathname?(which?must?refer?
to?an?existing,?accessible?file[必須是一個(gè)已經(jīng)存在,并且可訪問的文件])?and?the?least?significant(有效的)?8?bits[有效的最低8位]?of?proj_id?(which?must??be??nonzero)??to??generate??a??key_t??type??System?V?IPC?key,?suitable?
for?use?with?msgget(2),?semget(2),?or?shmget(2).? ?The?resulting?value?is?the?same?for?all?pathnames?that?name?the?same?file,?when?the??same?value??of??proj_id ?
is?used(如果文件名與proj_id的有效位全都相同的話,?則生成的key一定也是相同的).??The?value?returned?should?be?different?when?
the?(simultaneously?existing)?files?or?the?project?IDs?differ.
?
RETURN?VALUE? ?On?success,?the?generated?key_t?value?is?returned.??On?failure?-1?is?returned,?
with?errno?indicating?the?error?as?for?the?stat(2)?system?call.
總結(jié)
以上是生活随笔為你收集整理的Linux IPC实践(6) --System V消息队列(3)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQLSERVER 日志收缩
- 下一篇: localStorage、session