一直以前命令参数好高端,比如 ./nginx -s reload 重新加载配置文件, ./nginx -h 查看帮助文档, 还可以./nginx直接启动nginx,其实linux上其实提供了解析命令行参数的函数getopt_long(头文件getopt.h),特别容易使用,这些都是在webbench一个开源项目中get到的。

       

#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>


int clients=1;
int force=0;

static const struct option long_options[]=
{

{"help", no_argument, NULL, '?'},
{"version", no_argument, NULL, 'V'},
{"clients", required_argument, NULL, 'c'},
{"force", no_argument, &force, 1},
{NULL, 0, NULL, 0}
};

static void usage()
{
fprintf(stderr,
"webbench [option]... URL \n"
" -f|--force Don't wait for reply from server.\n"
" -?|-h|--help This information.\n"
" -c|--clients <n> Use n clients.\n"
" -V|--version Display program version.\n"
);
}

int main(int argc, char *argv[])
{
int opt = 0;
int options_index = 0;

while((opt=getopt_long(argc, argv, "Vfc:?h", long_options, &options_index)) != EOF){
switch(opt){
case 0 : break;
case 'f': force=1; printf("force = %d\n", force);break;
case 'V': printf("vaynedu 1.1.1\n");exit(0);
case '?': usage();exit(0);
case 'h': usage();exit(0);
case 'c': clients=atoi(optarg); printf("clients = %d\n", clients);break;
default : printf("input error,please input ./webbench -h\n");break;
}
}

printf(" vaynedu try to use getopt\n");

return 0;
}


输出结果演示:

          

linux解析命令行参数getopt_long_nginx


具体的使用方法和高端操作,看了两篇很好的博客,我也就不多BB了

​​linux-解析命令行选项getopt_long用法​​


​函数getopt(),及其参数optind​