隊列最大容量字節(jié)數(shù) 16384
隊列最大隊列容量數(shù) 16
key_t ftok(char* path,int id)使用說明:
ftok創(chuàng)建一個鍵,是內核中的隊列在外部的ID號,由于消息隊列處于內核中,只有創(chuàng)建者和內核知道隊列在內核里面的ID號,這樣其它的進程就無法知道內核里面隊列ID號,所以要關聯(lián)一個外部鍵進行關聯(lián)
id (1-255)
返回內核消息隊列的ID號
其它的注意就查看一下unix高級環(huán)境編程吧,或者有些問題需要討論就回我吧!!
server.c
#include "msg.h" #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char** argv) { int queid = open_msg("/root",100); while(1) { fputs("請輸入要發(fā)送的類型:1 or 2\\\\n", stdout); int type; scanf("%d",&type); switch(type) { case MYTYPE_ONE: { msg_send(queid,"MYTYPE_ONE", MYTYPE_ONE); break; } case MYTYPE_TWO: { msg_send(queid,"MYTYPE_TWO", MYTYPE_TWO); break; } default: { fputs("輸入類型錯誤,請重新輸入\\\\n",stdout); break; } } fputs("輸入:q 為退出,其它表示繼續(xù)\\\\n",stdout); if(getchar() == \\\'q\\\') { fputs("退出成功!\\\\n",stdout); break; } else { fputs("繼續(xù)發(fā)送消息\\\\n",stdout); } } //不發(fā)送退出需要獎隊列移除 del_que(queid); return 0; }
client.c
#include "msg.h" #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char** argv) { int queid = open_msg("/root",100); while(1) { fputs("請接收要發(fā)送的類型:1 or 2\\\\n", stdout); int type; scanf("%d",&type); switch(type) { case MYTYPE_ONE: { msg_rec(queid,MYTYPE_ONE); break; } case MYTYPE_TWO: { msg_rec(queid,MYTYPE_TWO); break; } default: { fputs("輸入類型錯誤,請重新輸入\\\\n",stdout); break; } } fputs("輸入:q 為退出,其它表示繼續(xù)\\\\n",stdout); if(getchar() == \\\'q\\\') { fputs("退出成功!\\\\n",stdout); break; } else { fputs("繼續(xù)發(fā)送消息\\\\n",stdout); } } //隊列移除 del_que(queid); return 0; }
msg.c
#include <sys/types.h> #include <sys/ipc.h> #include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/msg.h> #include<string.h> #include"msg.h" //如果存在隊列則打開,沒有則創(chuàng)建 int open_msg(char* path, int id) { //獲取IPC對象的一個鍵 key_t key = ftok(path, id); if(-1 == key) { perror("ftok\\\\n"); exit(1); } //創(chuàng)建一個隊列 int queid = msgget(key, IPC_CREAT|0666); if(-1 == queid) { perror("msgget\\\\n"); exit(1); } return queid; } //發(fā)送消息到隊列 void msg_send(key_t key,char* text, long msgtype) { //初始化內容 struct MSG tmp; memset(&tmp,sizeof(struct MSG),0); tmp.mytype = msgtype; strcpy(tmp.mytext,text); //發(fā)送消息 if(msgsnd(key, &tmp, TEXTSIZE, 0)) { perror("msgsnd\\\\n"); exit(1); } } //從消息隊列獲取消息并顯示 void msg_rec(key_t key,long msgtype) { struct MSG tmp; if(-1 == msgrcv(key, &tmp, TEXTSIZE, msgtype, MSG_NOERROR)) { perror("msgrcv\\\\n"); exit(1); } printf("receive content: %s\\\\n",tmp.mytext); } //刪除隊列,即使隊列里面還有消息也一起刪除 void del_que(key_t key) { if(msgctl(key,IPC_RMID,NULL)) { perror("msgsnd\\\\n"); exit(1); } }
msg.h
#ifndef MSG_H #define MSG_H #include <sys/types.h> #define TEXTSIZE 100 #define ARRYSIZE 2 #define MYTYPE_ONE 1 #define MYTYPE_TWO 2 struct MSG { long mytype; char mytext[TEXTSIZE]; }; int open_msg(char*,int); void msg_send(key_t,char*,long); #endif // end MSG_H
附件:http://down.51cto.com/data/2362206
更多關于云服務器,域名注冊,虛擬主機的問題,請訪問西部數(shù)碼官網(wǎng):m.ps-sw.cn