ubuntu下 C/C++程序读取设置环境变量

设置环境变量很简单比如:

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;	
		
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QMCY_jason

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值