
前言

平时我们在shell命令行上输入的命令都是应用程序,比如ls,ifconfig,vi等。我们下载的busybox源码中就包含着这些程序源码,那接下来我们来看看如何实现一个命令。

如何实现

我们先分析一下其他的命令,比如gcc:
gcc helloworld.c -o helloworld
复制
上面的编译指令中,gcc就是命令程序,然后后面的三个都是传给它的参数。程序是如何获取到参数的呢?我们都知道main函数的定义如下:
int main(int argc, char * argv[])
复制
argc是参数个数,argv是参数值。所以大家应该都知道如何获取参数了吧。
有了参数,我们就要进行解析了。这就有两种方法:
对参数进行一个一个的判断解析
使用getopt函数进行解析
第一种方式工作量非常大,所以我们来使用第二种方式。

getopt函数介绍

#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
复制
argc:参数个数,直接将main函数中的argc传给该函数。
argv:参数数组,直接将main函数中的argv传给该函数。
optstring: 选项字符串。
里面还有几个额外的全局变量:
extern char *optarg;
extern int optind, opterr, optopt;
复制
optarg: 保存选项参数
optind: 记录下一个检索位置
opterr: 是否将错误信息输出到stderr, 为0时表示不输出
optopt: 不在选项字符串optstring中的选项

选项字符串

getopt函数中有个optstring参数 ,就是选项字符串。用来指定选项,就比如上面gcc命令中的-o,它就是一个选项。
那如何给getopt传递选项字符串呢?举个例子:
a:b:cd::e
复制
这个选项字符串对应命令行就是-a ,-b ,-c ,-d, -e选项。
冒号表示参数,一个冒号就表示这个选项后面必须带有参数。这个参数可以和选项连在一起写,也可以用空格隔开。
两个冒号的就表示这个选项的参数是可选的,既可以有参数,也可以没有参数,但要注意有参数时,参数与选项之间不能有空格。

实例

#include <unistd.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
int ch;
printf("optind:%d,opterr:%d\n", optind, opterr);
printf("--------------------------\n");
while ((ch = getopt(argc, argv, "ab:c:de::")) != -1)
{
printf("optind: %d\n", optind);
switch (ch)
{
case 'a':
printf("option: -a\n\n");
break;
case 'b':
printf("option: -b\n");
printf("The argument of -b is %s\n\n", optarg);
break;
case 'c':
printf("option: -c\n");
printf("The argument of -c is %s\n\n", optarg);
break;
case 'd':
printf("option: -d\n");
break;
case 'e':
printf("option: -e\n");
printf("The argument of -e is %s\n\n", optarg);
break;
case '?':
printf("Unknown option: %c\n",(char)optopt);
break;
}
}
return 0;
}
复制
运行结果:
-b选项没有跟参数则报错!

文章转载自嵌入式软件开发交流,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。