设置环境变量很简单比如:
export QMCY_LOCAL_PORT=8888
追加的话
export QMCY_LOCAL_PORT=$QMCY_LOCAL_PORT:8000
可以通过echo回显
读取的话 main函数多加一个env参数 一个字符串数组 然后遍历这个数组 即可
使用的时候 如下:
bool QMCY_APP::Init(std::string &config_file, char *env[])
{char *file_content = nullptr;int size = 0;unsigned seed = time(0);srand(seed);if(config_file.empty()){std::cout<<"config file is null"<<std::endl;return false;}FILE * fp = fopen(config_file.c_str(),"r");if(fp == NULL){return false;}fseek(fp, 0, SEEK_END);size = ftell(fp);file_content = (char *)malloc(size+1);if(file_content){fseek(fp, 0, SEEK_SET);fread(file_content,size,1,fp);ReadConfig(file_content);free(file_content);}fclose(fp); int i = 0;char key[20] ={0},value[30]={0};for(; env[i]; i++){std::string temp = env[i];std::size_t found = temp.find(m_basic_info.server_ip_name);if(found!= std::string::npos){int converted = sscanf(temp.c_str(),"%[^=]=%s",key,value);if(converted == 2){m_basic_info.server_ip = value; }}found = temp.find(m_basic_info.server_port_name);if(found!= std::string::npos){int converted = sscanf(temp.c_str(),"%[^=]=%s",key,value);if(converted == 2){m_basic_info.server_port = atoi(value);}}found = temp.find(m_basic_info.local_port_name);if(found!= std::string::npos){int converted = sscanf(temp.c_str(),"%[^=]=%s",key,value);if(converted == 2){//std::cout<<"local port :"<<key<<" :"<<value<<std::endl;m_basic_info.local_port = atoi(value); }}}if(m_basic_info.local_port<1024|| m_basic_info.local_port >65535 ){m_basic_info.local_port = 8888;}if(m_basic_info.server_port<1024|| m_basic_info.server_port >65535 ){m_basic_info.server_port = 8888;}zlog_info(g_zlog,"APP run info:[server ip = %s,server port=%d, local port = %d]",m_basic_info.server_ip.c_str(),m_basic_info.server_port,m_basic_info.local_port);std::string posturi = "http://";posturi.append(m_basic_info.server_ip);posturi.append(":"); posturi.append(std::to_string(m_basic_info.server_port)); m_http_client = std::make_shared<httplib::Client>(posturi);//m_log = HANA<LOG>::GetHANA();m_thread_pool = std::make_shared<BlackBox>(MAX_THREADS,MAX_QUEUE_SIZE);m_thread_pool->init();//m_queue = std::make_shared<BlockQueue<LED_MSG>>(30);m_inner_queue = std::make_shared<BlockQueue<INNER_MSG>>(30);return true; }