前言
本章以代码形式提供命令行解析Demo,虽然解析形式有千万种,但我最中这一种啊。其实是在阅读源码时候看到的,我就给提出来了。
代码
#include <getopt.h>
std::atomic<int> g_msgCount(1);
class Args
{
public:
Args()
: body("msgbody for test"),
thread_count(std::thread::hardware_concurrency()),
broadcasting(false),
syncpush(false),
SelectUnactiveBroker(false),
IsAutoDeleteSendCallback(false),
retrytimes(5),
PrintMoreInfo(false) {}
public:
std::string namesrv;
std::string namesrv_domain;
std::string groupname;
std::string topic;
std::string body;
int thread_count;
bool broadcasting;
bool syncpush;
bool SelectUnactiveBroker; // default select active broker
bool IsAutoDeleteSendCallback;
int retrytimes; // default retry 5 times;
bool PrintMoreInfo;
};
static bool ParseArgs(int argc, char* argv[], Args* info);
int main(int argc, char* argv[])
{
Args info;
if (!ParseArgs(argc, argv, &info))
{
exit(-1);
}
...
}
static bool ParseArgs(int argc, char* argv[], Args* info)
{
int ch;
while ((ch = getopt(argc, argv, "n:i:g:t:m:c:b:s:h:r:T:bu")) != -1)
{
switch (ch) {
case 'n':
info->namesrv.insert(0, optarg);
break;
case 'i':
info->namesrv_domain.insert(0, optarg);
break;
case 'g':
info->groupname.insert(0, optarg);
break;
case 't':
info->topic.insert(0, optarg);
break;
case 'm':
g_msgCount.store(atoi(optarg)); // atomic 赋值方式
break;
case 'c':
info->body.insert(0, optarg);
break;
case 'b':
info->broadcasting = true;
break;
case 's':
info->syncpush = true;
break;
case 'r':
info->retrytimes = atoi(optarg);
break;
case 'u':
info->SelectUnactiveBroker = true;
break;
case 'T':
info->thread_count = atoi(optarg);
break;
case 'v':
info->PrintMoreInfo = true;
break;
case 'h':
help();
return false;
default:
help();
return false;
}
}
if (info->groupname.empty() || info->topic.empty() || (info->namesrv_domain.empty() && info->namesrv.empty()))
{
std::cout << "please use -g to setup groupname and -t setup topic \n";
help();
return false;
}
return true;
}