Linux關(guān)于消息隊(duì)列的使用 |
發(fā)布時(shí)間: 2012/8/10 14:21:21 |
今天完成消息隊(duì)列的使用。
消息隊(duì)列類似FIFO,但是可以實(shí)現(xiàn)隨機(jī)查詢。 主要函數(shù):msgget,msgsnd,msgrcv,msgctl 實(shí)驗(yàn)實(shí)現(xiàn)兩個(gè)進(jìn)程之間的通信。 一個(gè)發(fā)送,一個(gè)接受。并不需要額外實(shí)現(xiàn)進(jìn)程同步。 源代碼來(lái)自華清遠(yuǎn)見(jiàn): 發(fā)送: #include #include #include #include #include #include #include #define BUFFER_SIZE 512 struct message { long msg_type; char msg_text[BUFFER_SIZE]; }; int main() { int qid; key_t key; struct message msg; //ftok根據(jù)不同路徑和關(guān)鍵字產(chǎn)生標(biāo)準(zhǔn)的KEY if((key = ftok(".", 'a')) == -1) { perror("ftok"); exit(1); } if((qid = msgget(key, IPC_CREAT|0666)) == -1)//創(chuàng)建 { perror("msgget"); exit(1); } printf("open queue %dn", qid); while(1) { printf("enter some message to the queue:"); if((fgets(msg.msg_text, BUFFER_SIZE, stdin)) == NULL) { puts("no message"); exit(1); } msg.msg_type = getpid();//消息類型為進(jìn)程號(hào) if((msgsnd(qid, &msg, strlen(msg.msg_text), 0)) < 0)//發(fā)送消息 { perror("message posted"); exit(1); } if(strncmp(msg.msg_text, "quit", 4) == 0) { break; } } exit(0); } 接收: #include #include #include #include #include #include #include #define BUFFER_SIZE 512 struct message { long msg_type; char msg_text[BUFFER_SIZE]; }; int main() { int qid; key_t key; struct message msg; if((key = ftok(".", 'a')) == -1) { perror("ftok"); exit(1); } if((qid = msgget(key, IPC_CREAT|0666)) == -1)//創(chuàng)建 { perror("msgget"); exit(1); } printf("open queue %dn", qid); do { memset(msg.msg_text, 0, BUFFER_SIZE); if(msgrcv(qid, (void*)&msg, BUFFER_SIZE, 0, 0) < 0)//接收消息 { perror("msgrcv"); exit(1); } printf("the message from process %d : %s", msg.msg_type, msg.msg_text); }while(strncmp(msg.msg_text, "quit", 4)); if((msgctl(qid, IPC_RMID, NULL)) < 0)//從系統(tǒng)內(nèi)核移走消息隊(duì)列 { perror("msgctl"); exit(1); } exit(0); } 打開兩個(gè)終端,1號(hào)發(fā)送,2號(hào)接收 本文出自:億恩科技【www.allwellnessguide.com】 服務(wù)器租用/服務(wù)器托管中國(guó)五強(qiáng)!虛擬主機(jī)域名注冊(cè)頂級(jí)提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM] |