Linux 2.4.22 限制:
- #include "msg.h"
- #include
- #include
- #include
- int main(int argc, char** argv)
- {
- int queid = open_msg("/root", 100);
- while(1)
- {
- fputs("請輸入要發送的類型: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 為退出,其它表示繼續\n", stdout);
- if(getchar() == 'q')
- {
- fputs("退出成功!\n", stdout);
- break;
- }
- else
- {
- fputs("繼續發送消息\n", stdout);
- }
- }
- // 不發送退出需要將佇列移除
- del_que(queid);
- return 0;
- }
- #include "msg.h"
- #include
- #include
- #include
- int main(int argc, char** argv)
- {
- int queid = open_msg("/root", 100);
- while(1)
- {
- fputs("請接收要發送的類型: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 為退出,其它表示繼續\n", stdout);
- if(getchar() == 'q')
- {
- fputs("退出成功!\n", stdout);
- break;
- }
- else
- {
- fputs("繼續發送消息\n", stdout);
- }
- }
- // 佇列移除
- del_que(queid);
- return 0;
- }
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include "msg.h"
- // 如果存在佇列則開啟,沒有則建立
- int open_msg(char* path, int id)
- {
- // 獲取 IPC 物件的一個鍵值
- key_t key = ftok(path, id);
- if(-1 == key)
- {
- perror("ftok\n");
- exit(1);
- }
- // 建立一個佇列
- int queid = msgget(key, IPC_CREAT | 0666);
- if(-1 == queid)
- {
- perror("msgget\n");
- exit(1);
- }
- return queid;
- }
- // 發送消息到佇列
- 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);
- // 發送消息
- 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);
- }
- }
- #ifndef MSG_H
- #define MSG_H
- #include
- #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