getopt32 分析

本文深入解读getopt32函数,详细阐述如何解析命令行参数,包括选项标识、标志生成、参数处理及应用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

uint32_t getopt32(char **argv, const char *applet_opts,…)
命令行选项必须声明为类似const char *applet_opts的字符串形式, 例如:
flags = getopt32(argv, "rnug");

如果其中一个选项被找到了, 就有一个标志值(unsigned long类型)添加到返回值中。

标志值由字符在applet_opts种的位置决定, 例如在上例中:
flags = getopt32(argv, "rnug");

"r"将添加1 (0比特位)
"n"将添加2 (1比特位)
"u"将添加4 (2比特位)
"g"讲添加8 (3比特位)

等等, 你也可以通过位域方式查看返回值,每个选项就是其中一位.

一旦退出, 全局变量optind就被设置,因此如果你做argc -= optind; argv+= optind; argc就会等于剩下的非选项的参数个数,第一个放在argv[0],下一个放在argv[1]等等(选项和它们的参数在argv[optind]之前都会被移到argv[]中).

":"如果一个选项需要一个参数, 那就在applet_opts字符后面添加":"然后提供指向参数的指针. 例如:
  char *pointer_to_arg_for_a;
  char *pointer_to_arg_for_b;
  char *pointer_to_arg_for_c;
  char *pointer_to_arg_for_d;

  flags = getopt32(argv, "a:b:c:d:",
  &pointer_to_arg_for_a, &pointer_to_arg_for_b,
  &pointer_to_arg_for_c, &pointer_to_arg_for_d);
指针类型(char* 或 llist_t *)可以由"::"特殊分隔符控制,该分隔符由外部字符串opt_complementary设置(详细信息请看下面) 

"::" 如果选项有一个可选参数, 那就在applet_opts字符后面添加一个"::"并提供一个存储参数的指针. 注意可选参数必需紧跟着选项: -oparam而不是-o param.

"+" 如果applet_opts字符串第一个字符是加号, 那就argv数组中一旦遇上非选项字符就马上停止选项处理. 对于像env那样的applet就不会处理参数为子程序了: env -i ls -d /
这里我们希望env仅仅处理'-i'不是'-d'.

const char *applet_long_options
该结构体允许你定义长选项:
static const char applet_longopts[] ALIGN1 =
 //"name" has_arg val
 "verbose" No_argument "v";
 applet_long_options = applet_longopts;

结构体的最后一个成员(val)通常在applet_opts里面设置用来匹配短选项. 如果在applet_opts里面没有匹配到, 如是:
– 短选项的下一个位置的比特数
– 如果has_arg不是"No_argument", 也可以使用ptr作为参数
– opt_complementary也可以影响到它.

注意: 一个好的applet可以让长参数可配置,通过配置处理而不是必需的特征. 当前标准命名配置选项为CONFIG_FEATURE_<applet>_LONG_OPTIONS.

const char *opt_complementary
":" 冒号用来分隔两个或多个字符并/或字符组以及特殊字符(表示要检查一些状态)

"abc" 如果指定了两个或多个字符组, 第一个字符就是主选项,其余的字符是副选项。 如果找到了主选项, 他们的标志就出现了即使没有在命令行中指定他们. 例如:

opt_complementary = "abc";
flags = getopt32(argv, "abcd");

如果getopt()找到命令行中的"-a", getopt32的返回值就好比找到了"-a -b -c".

"ww" 调整有计数器关联来指示选项的发生次数的双选项. 例如ps applet的需要:
 如果w给定一次, GNU ps设置宽度为132,
 如果w给定的多于一次, 就是"无限制"

 int w_counter = 0; //必需初始化
 opt_complementary = "ww";
 getopt32(argv, "w", &w_counter);
 if (w_counter)
  width = (w_counter == 1) ? 132 : INT_MAX;
 else
  get_terminal_width(…&width…);

 w_counter是一个指向整数的指针, 它得在所有选项参数沉下去之后传给getopt32().

 例如: 接受多个-v来表示冗长级别和每一个-b optarg级别,添加optarg到my_b. 最后, 如果给定了b就关闭c或者反过来:
 llist_t *my_b = NULL;
 int verbose_level = 0;
 opt_complementary = "vv:b::b-c:c-b";
 f = getopt32(argv, "vb:c", &my_b, &verbose_level);
 if (f & 2) //-c在-b后面, 取消设置-b标志
  while (my_b) dosomething_with(llist_pop(&my_b));
 if (my_b) //但是如果指定了-b就存储llist
  free_llist(my_b);
 if (verbose_level) printf("verbose level is %dn", verbose_level);

特殊字符:
"-" opt_complementary组中的起始字符是横线强制要求所有参数作为选项来看待,尽管它们没有横线打头. 这种情况下下一个字符不能是数字(0-9), 使用':'或行结束符. 例如:
opt_complementary = "-:w-x:x-w";
getopt32(argv, "wx");
允许不适用横线而给定所有参数(./program w x), 就像带有横线一样(./program -x).
NB: getopt32()会泄露一小部分内存如果你使用这个项. 如果有递归调用getopt32()的可能就不要使用.

"–" opt_complementary开始的双横线表示argv[1]字符串应该总是作为选项来看待, 尽管不是以"-"做前缀. 这在诸如"ar"和"tar"的applet中有特别语义:
tar xvf foo.tar
NB: 如果你使用这个项,getopt32()将会泄露一小部分内存. 如果有递归调用getopt32()的可能就不要使用.

"-N" opt_complementary组的起始横线紧跟一个数字(0-9)意味着至少要在命令行里面出现N个非选项的参数.

"=N" opt_complementary起始的等号符紧跟打个数字(0-9)意味着要在命令行里出现恰好N个非选项参数.

分析以下代码: uint32_t FAST_FUNC getopt32(char **argv, const char *applet_opts, ...) { int argc; unsigned flags = 0; unsigned requires = 0; t_complementary complementary[33]; /* last stays zero-filled */ char first_char; int c; const unsigned char *s; t_complementary *on_off; va_list p; #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG const struct option *l_o; struct option *long_options = (struct option *) &bb_null_long_options; #endif unsigned trigger; char **pargv; int min_arg = 0; int max_arg = -1; #define SHOW_USAGE_IF_ERROR 1 #define ALL_ARGV_IS_OPTS 2 #define FIRST_ARGV_IS_OPT 4 int spec_flgs = 0; /* skip 0: some applets cheat: they do not actually HAVE argv[0] */ argc = 1; while (argv[argc]) argc++; va_start(p, applet_opts); c = 0; on_off = complementary; memset(on_off, 0, sizeof(complementary)); /* skip bbox extension */ first_char = applet_opts[0]; if (first_char == '!') applet_opts++; /* skip GNU extension */ s = (const unsigned char *)applet_opts; if (*s == '+' || *s == '-') s++; while (*s) { if (c >= 32) break; on_off->opt_char = *s; on_off->switch_on = (1 << c); if (*++s == ':') { on_off->optarg = va_arg(p, void **); while (*++s == ':') continue; } on_off++; c++; } #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG if (applet_long_options) { const char *optstr; unsigned i, count; count = 1; optstr = applet_long_options; while (optstr[0]) { optstr += strlen(optstr) + 3; /* skip NUL, has_arg, val */ count++; } /* count == no. of longopts + 1 */ long_options = alloca(count * sizeof(*long_options)); memset(long_options, 0, count * sizeof(*long_options)); i = 0; optstr = applet_long_options; while (--count) { long_options[i].name = optstr; optstr += strlen(optstr) + 1; long_options[i].has_arg = (unsigned char)(*optstr++); /* long_options[i].flag = NULL; */ long_options[i].val = (unsigned char)(*optstr++); i++; } for (l_o = long_options; l_o->name; l_o++) { if (l_o->flag) continue; for (on_off = complementary; on_off->opt_char; on_off++) if (on_off->opt_char == l_o->val) goto next_long; if (c >= 32) break; on_off->opt_char = l_o->val; on_off->switch_on = (1 << c); if (l_o->has_arg != no_argument) on_off->optarg = va_arg(p, void **); c++; next_long: ; } /* Make it unnecessary to clear applet_long_options * by hand after each call to getopt32 */ applet_long_options = NULL; } #endif /* ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG */ for (s = (const unsigned char *)opt_complementary; s && *s; s++) { t_complementary *pair; unsigned *pair_switch; if (*s == ':') continue; c = s[1]; if (*s == '?') { if (c < '0' || c > '9') { spec_flgs |= SHOW_USAGE_IF_ERROR; } else { max_arg = c - '0'; s++; } continue; } if (*s == '-') { if (c < '0' || c > '9') { if (c == '-') { spec_flgs |= FIRST_ARGV_IS_OPT; s++; } else spec_flgs |= ALL_ARGV_IS_OPTS; } else { min_arg = c - '0'; s++; } continue; } if (*s == '=') { min_arg = max_arg = c - '0'; s++; continue; } for (on_off = complementary; on_off->opt_char; on_off++) if (on_off->opt_char == *s) goto found_opt; /* Without this, diagnostic of such bugs is not easy */ bb_error_msg_and_die("NO OPT %c!", *s); found_opt: if (c == ':' && s[2] == ':') { on_off->param_type = PARAM_LIST; continue; } if (c == '+' && (s[2] == ':' || s[2] == '\0')) { on_off->param_type = PARAM_INT; s++; continue; } if (c == ':' || c == '\0') { requires |= on_off->switch_on; continue; } if (c == '-' && (s[2] == ':' || s[2] == '\0')) { flags |= on_off->switch_on; on_off->incongruously |= on_off->switch_on; s++; continue; } if (c == *s) { on_off->counter = va_arg(p, int *); s++; } pair = on_off; pair_switch = &pair->switch_on; for (s++; *s && *s != ':'; s++) { if (*s == '?') { pair_switch = &pair->requires; } else if (*s == '-') { if (pair_switch == &pair->switch_off) pair_switch = &pair->incongruously; else pair_switch = &pair->switch_off; } else { for (on_off = complementary; on_off->opt_char; on_off++) if (on_off->opt_char == *s) { *pair_switch |= on_off->switch_on; break; } } } s--; } opt_complementary = NULL; va_end(p); if (spec_flgs & (FIRST_ARGV_IS_OPT | ALL_ARGV_IS_OPTS)) { pargv = argv + 1; while (*pargv) { if (pargv[0][0] != '-' && pargv[0][0] != '\0') { /* Can't use alloca: opts with params will * return pointers to stack! * NB: we leak these allocations... */ char *pp = xmalloc(strlen(*pargv) + 2); *pp = '-'; strcpy(pp + 1, *pargv); *pargv = pp; } if (!(spec_flgs & ALL_ARGV_IS_OPTS)) break; pargv++; } } /* In case getopt32 was already called: * reset the libc getopt() function, which keeps internal state. * run_nofork_applet() does this, but we might end up here * also via gunzip_main() -> gzip_main(). Play safe. */ #ifdef __GLIBC__ optind = 0; #else /* BSD style */ optind = 1; /* optreset = 1; */ #endif /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */ /* Note: just "getopt() <= 0" will not work well for * "fake" short options, like this one: * wget $'-\203' "Test: test" http://kernel.org/ * (supposed to act as --header, but doesn't) */ #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG while ((c = getopt_long(argc, argv, applet_opts, long_options, NULL)) != -1) { #else while ((c = getopt(argc, argv, applet_opts)) != -1) { #endif /* getopt prints "option requires an argument -- X" * and returns '?' if an option has no arg, but one is reqd */ c &= 0xff; /* fight libc's sign extension */ for (on_off = complementary; on_off->opt_char != c; on_off++) { /* c can be NUL if long opt has non-NULL ->flag, * but we construct long opts so that flag * is always NULL (see above) */ if (on_off->opt_char == '\0' /* && c != '\0' */) { /* c is probably '?' - "bad option" */ goto error; } } if (flags & on_off->incongruously) goto error; trigger = on_off->switch_on & on_off->switch_off; flags &= ~(on_off->switch_off ^ trigger); flags |= on_off->switch_on ^ trigger; flags ^= trigger; if (on_off->counter) (*(on_off->counter))++; if (optarg) { if (on_off->param_type == PARAM_LIST) { llist_add_to_end((llist_t **)(on_off->optarg), optarg); } else if (on_off->param_type == PARAM_INT) { //TODO: xatoi_positive indirectly pulls in printf machinery *(unsigned*)(on_off->optarg) = xatoi_positive(optarg); } else if (on_off->optarg) { *(char **)(on_off->optarg) = optarg; } } } /* check depending requires for given options */ for (on_off = complementary; on_off->opt_char; on_off++) { if (on_off->requires && (flags & on_off->switch_on) && (flags & on_off->requires) == 0 ) { goto error; } } if (requires && (flags & requires) == 0) goto error; argc -= optind; if (argc < min_arg || (max_arg >= 0 && argc > max_arg)) goto error; option_mask32 = flags; return flags; error: if (first_char != '!') bb_show_usage(); return (int32_t)-1; }
最新发布
08-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值