设置环境变量很简单比如:
export QMCY_LOCAL_PORT=8888
追加的话
export QMCY_LOCAL_PORT=$QMCY_LOCAL_PORT:8000
可以通过echo回显
读取的话 main函数多加一个env参数 一个字符串数组 然后遍历这个数组 即可
文章来源:https://www.toymoban.com/news/detail-537574.html
使用的时候 如下:文章来源地址https://www.toymoban.com/news/detail-537574.html
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;
}
到了这里,关于ubuntu下 C/C++程序读取设置环境变量的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!