您的位置:首页 > 运维架构 > Linux

Glib解析命令行参数

2016-01-26 11:44 525 查看
#include <stdio.h>
#include <glib.h>
static gint max_user = 20;
static gint time_out = 2;
static gint listen_port = 8852;
static gchar listen_ip[32] = {"0.0.0.0"};
static gboolean debug = FALSE;
static GOptionEntry entries[] =
{
{
"listen",               /*参数长名*/
'l',                    /*短参数名*/
0,                      /*falg*/
G_OPTION_ARG_STRING,    /*参数类型*/
listen_ip,              /*参数变量*/
"Set lisetn ip",        /*选项说明*/
"listen_ip"             /*参数选项占位符说明*/
},
{"port",'p',0,G_OPTION_ARG_INT,
&listen_port,"listen port","port"},
{"max_user",'m',0,G_OPTION_ARG_INT,
&max_user,"Define the max user for server","M"},
{"time_out",'t',0,G_OPTION_ARG_INT,
&time_out,"Stop connection when idel time over N","N"},
{"debug",'d',0,G_OPTION_ARG_NONE,
&debug,"Debug mode",NULL},
};
int main(int argc ,char **argv)
{
GError *error = NULL;
GOptionContext *context = NULL;
context = g_option_context_new("-test tree model performance");
g_option_context_add_main_entries(context,entries,NULL);
// 扩展的选项
//context 自带help选项,支持 --help,-h,-?,--help-all, 可以通过设置去掉
//g_option_context_set_help_enabled(context,FALSE);
//忽略错误的选项,有错误的选项默认会报错,忽略掉就不报错
//g_option_context_set_ignore_unknown_options(context,TRUE);
// help 里面打上一段文字说明,可以搞点版本号,版权说明什么的
g_option_context_set_summary(context," Glib Test by Andy\n mhpmii@126.com\n");
if(!g_option_context_parse(context,&argc,&argv,&error)) {
g_print("option parseing failed : %s\n",error->message);
return -1;
}
g_option_context_free(context);
g_print("The Server Run at %s:%d\nmax uer :%d ,time out : %d  debug[%s]\n",
listen_ip,
listen_port,
max_user,
time_out,
debug?"TRUE":"FALSE");
return 0;
}
/***************************************/
// 其他说明
/***************************************/
//[1] flag 一般不需设置,填0
/*
typedef enum
{
G_OPTION_FLAG_HIDDEN		= 1 << 0,   //设置选项不在--help中显示
G_OPTION_FLAG_IN_MAIN		= 1 << 1,
G_OPTION_FLAG_REVERSE		= 1 << 2,
G_OPTION_FLAG_NO_ARG		= 1 << 3,
G_OPTION_FLAG_FILENAME	= 1 << 4,
G_OPTION_FLAG_OPTIONAL_ARG    = 1 << 5,
G_OPTION_FLAG_NOALIAS	        = 1 << 6
} GOptionFlags;
*/
//[2]参数类型的对应关系
/*
G_OPTION_ARG_NONE           gboolean
G_OPTION_ARG_STRING         gchar*
G_OPTION_ARG_INT            gint
G_OPTION_ARG_FILENAME       gchar*
G_OPTION_ARG_STRING_ARRAY   gchar**
G_OPTION_ARG_FILENAME_ARRAY gchar**
*/

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  glib 命令行解析 linux