mkdir.c源码学习笔记
参数解析篇:
static struct option const longopts[] =
{
{GETOPT_SELINUX_CONTEXT_OPTION_DECL},
{"mode", required_argument, NULL, 'm'},
{"parents", no_argument, NULL, 'p'},
{"verbose", no_argument, NULL, 'v'},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
while ((optc = getopt_long (argc, argv, "pm:vZ", longopts, NULL)) != -1)
{
switch (optc)
{
case 'p':
options.make_ancestor_function = make_ancestor;
break;
case 'm':
specified_mode = optarg;
break;
case 'v': /* --verbose */
options.created_directory_format = _("created directory %s");
break;
case 'Z':
if (is_smack_enabled ())
{
/* We don't yet support -Z to restore context with SMACK. */
scontext = optarg;
}
else if (is_selinux_enabled () > 0)
{
if (optarg)
scontext = optarg;
else
options.set_security_context = true;
}
else if (optarg)
{
error (0, 0,
_("warning: ignoring --context; "
"it requires an SELinux/SMACK-enabled kernel"));
}
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (EXIT_FAILURE);
}
}
源码调用函数getopt_long()函数进行长选项参数解析,mkdir可接受的短选项共4个:-p,-m,-v,-Z(pm:vZ)。其中,-m选项必须带参数。mkdir可接受的长选项共6个:--context,--mode,--parents,--verbose,--help,--version,其中与短选项对应的参数分别是:--parents,--mode,--verbose,--context。
解析完选项后,判断是否有为mkdir传入文件夹名参数,文件夹名称是必须传入的,如:mkdir filename。
if (optind == argc)
{
error (0, 0, _("missing operand"));
usage (EXIT_FAILURE);
}
optind是当前参数的下表索引,argc是参数的个数,所以当optind==argc时,解析完选项参数后,不存在要创建的文件夹名,所以退出。