glib学习笔记之六——处理命令行参数

时间:2022-06-01 22:02:25
官方文档:http://developer.gnome.org/glib/stable/glib-Commandline-option-parser.html

在connman中使用GOptionEntry结构体处理命令行参数,结构体形式如下:

static GOptionEntry options[] = {
{ "debug", 'd', G_OPTION_FLAG_OPTIONAL_ARG,
G_OPTION_ARG_CALLBACK, parse_debug,
"Specify debug options to enable", "DEBUG" },
{ "device", 'i', 0, G_OPTION_ARG_STRING, &option_device,
"Specify networking device or interface", "DEV" },
{ "nodevice", 'I', 0, G_OPTION_ARG_STRING, &option_nodevice,
"Specify networking interface to ignore", "DEV" },
{ "plugin", 'p', 0, G_OPTION_ARG_STRING, &option_plugin,
"Specify plugins to load", "NAME,..." },
{ "noplugin", 'P', 0, G_OPTION_ARG_STRING, &option_noplugin,
"Specify plugins not to load", "NAME,..." },
{ "wifi", 'W', 0, G_OPTION_ARG_STRING, &option_wifi,
"Specify driver for WiFi/Supplicant", "NAME" },
{ "nodaemon", 'n', G_OPTION_FLAG_REVERSE,
G_OPTION_ARG_NONE, &option_detach,
"Don't fork daemon to background" },
{ "nodnsproxy", 'r', G_OPTION_FLAG_REVERSE,
G_OPTION_ARG_NONE, &option_dnsproxy,
"Don't enable DNS Proxy" },
{ "compat", 'c', 0, G_OPTION_ARG_NONE, &option_compat,
"(obsolete)" },
{ "version", 'v', 0, G_OPTION_ARG_NONE, &option_version,
"Show version information and exit" },
{ NULL },
};
建立结构体之后,创建context,将context与GOptionEntry关联,然后将命令行参数传入到context进行分析
        context = g_option_context_new(NULL);
g_option_context_add_main_entries(context, options, NULL);

if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
if (error != NULL) {
g_printerr("%s\n", error->message);
g_error_free(error);
} else
g_printerr("An unknown error occurred\n");
exit(1);
}

最后,分析的过程会将GOptionEntry结构体定义的options中的各个标记进行相应的处理