1. 程式人生 > 實用技巧 >linux程序間通訊之訊息佇列

linux程序間通訊之訊息佇列

專案背景:

  系統設計時為了減少模組之間的耦合關係,另外也為了使團隊的開發效率最大化,將資料的互動設計成訊息佇列,可以讓開發人員工資完成各自的程式碼介面,然後部署在同一臺物理機上聯調,加快專案進度。

專案設計:

  訊息佇列的寫資料端(簡稱client)向linux訊息佇列中放入資料,讀資料端(簡稱Server)從linux訊息佇列拿取資料。clint和server通過一致的msg_queue_id來確定使用的訊息佇列例項。

程式碼實現:

  介面的實現檔案.c

 1 /*
 2     Time:2020/10/13
 3     Auth: Semon
 4     功能描述:
 5         linux程序間通訊介面實現
6 */ 7 8 #include "linuxMsgQueue.h" 9 10 /* 11 * 功能描述:建立一個linux的程序間通訊之訊息佇列 12 * 返回值: 13 * 一個以key命名的訊息佇列的識別符號, 14 */ 15 int create_msg_queue(void){ 16 key_t key = ftok("/opt", 0x6666); 17 if(key < 0) 18 { 19 perror("ftok"); 20 return -1; 21 } 22 //建立訊息佇列 23
int msg_queue_id = msgget(key, 0666 | IPC_CREAT); 24 if(msg_queue_id == -1) 25 { 26 fprintf(stderr, "msgget failed with error: %d\n", errno); 27 //exit(EXIT_FAILURE); 28 } 29 printf("create msg queue successful.\n"); 30 return msg_queue_id; 31 } 32 /* 33 * 功能描述:
34 * 向訊息佇列寫入字串 35 * 返回值: 36 * 傳送是否成功 37 */ 38 int write_msg_to_queue(long int msg_id, const char* data){ 39 struct msg_data pMsg; 40 pMsg.msg_type = 1; 41 strncpy(pMsg.msg,data,strlen(data)+1); 42 printf("write_msg_to_queue inner. msg:%s data:%s \n",pMsg.msg,data); 43 int ret = msgsnd(msg_id, (void*)&pMsg, MAX_TEXT, IPC_NOWAIT); 44 if(-1 == ret){ 45 printf("send msg to linux queue failed. ret:%d\n",ret); 46 }else{ 47 printf("write msg:%s to queue successful.ret:%d\n",pMsg.msg,ret); 48 } 49 return ret; 50 } 51 /* 52 * 功能描述: 53 * 從訊息佇列讀取字串 54 * 返回值: 55 * 讀取是否成功 56 */ 57 int read_msg_from_queue(int msg_queue_id,int msg_type,struct msg_rData *pData){ 58 int ret = msgrcv(msg_queue_id, (void*)pData, BUFSIZ, msg_type, 0); 59 if(-1 == ret){ 60 printf("read msg from linux queue failed.\n"); 61 } 62 printf("read msg:%s. \n",pData->msg); 63 return 0; 64 } 65 /* 66 * 功能描述: 67 * 關閉訊息佇列 68 * 返回值: 69 * void 70 */ 71 void close_linux_queue(int msg_queue_id){ 72 printf("will be closed linux queue,msg_queue_id:%d\n",msg_queue_id); 73 msgctl(msg_queue_id, IPC_RMID, NULL); 74 }

介面的定義檔案.h

#ifndef JUDGE_LINUXMSGQUEUE_H
#define JUDGE_LINUXMSGQUEUE_H

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <errno.h>

#define MAX_TEXT  2560
//write
struct msg_data{
    long int msg_type;
    char msg[MAX_TEXT];
};
//read
struct msg_rData
{
    long int msg_type;
    char msg[BUFSIZ];
};
int create_msg_queue();
int write_msg_to_queue(long int msg_type, const char* data);
int read_msg_from_queue(int msg_queue_id,int msg_type,struct msg_rData *pData);
void close_linux_queue(int msg_queue_id);
#endif //JUDGE_LINUXMSGQUEUE_H