日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > linux >内容正文

linux

Linux IPC实践(6) --System V消息队列(3)

發(fā)布時(shí)間:2023/12/4 linux 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linux IPC实践(6) --System V消息队列(3) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

消息隊(duì)列綜合案例

消息隊(duì)列實(shí)現(xiàn)回射客戶/服務(wù)器

?

server進(jìn)程接收時(shí),?指定msgtyp0,?從隊(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)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。