getopt是linux下解析命令行参数的api。以linux内核代码的一个例子来说明:

 

static void cmdline(int argc, char *argv[])
{
    int opt;
    progname = basename(argv[0]);

while ((opt = getopt(argc, argv, "+lci:m:")) != -1) {
        switch (opt) {
        case 'l':
            if (mode)
                print_wrong_arg_exit();
            mode = list;
            break;
        case 'i':
            /* only allow -i with -m or no option */
            if (mode && mode != show)
                print_wrong_arg_exit();
            interval = atoi(optarg);
            break;
        case 'm':
            if (mode)
                print_wrong_arg_exit();
            mode = show;
            show_monitors_param = optarg;
            break;
        case 'c':
            wake_cpus = 1;
            break;
        default:
            print_wrong_arg_exit();
        }
    }
    if (!mode)
        mode = show_all;
}

getopt仅支持"-v"类型的带参以及不带参数的命令行参数解析,包含"--v"一对短横线的复杂命令行参数请使用其他api。

函数原型

       int getopt(int argc, char * const argv[],
                  const char *optstring);

argc和argv都懂得,optstring告诉getopt需要哪些命令以及哪些命令需要参数,以"+lci:m:"为例,带"+"的参数不多见忽略掉,'l'和'c'是不带参数的命令选项,'i:'和'm:'是带参数的命令选项,两者通过':'进行区分。getopt获取命令以后参数保存在全局变量optarg中。

包括optarg在内,getopt使用三个全局变量来保存状态(该函数是线程非安全的,多线程使用需要自己加保护)。

optarg,保存命令的参数,如果有的话。

optind,下一次getopt时指向的argv指针的索引 。

optopt,最后一个已知选项。

optind用来获取除了命令行命令和参数以外的其他内容,比如命令行的最后添加一个默认参数配置文件。

上面的例子是一个直观的解析用法,再来一个推荐的解析方式。

    while ((opt = getopt(argc, argv, "+lci:m:")) != -1) {
        switch (opt) {

        case 'A':
            /* enables "shutdown" command */
            settings.shutdown_command = true;
            break;

case 'a':
            /* access for unix domain socket, as octal mask (like chmod)*/
            settings.access= strtol(optarg,NULL,8);
            break;

default:

break;

}

settings是一个入参结构体,对应入参的命令和参数

struct settings {
    size_t maxbytes;
    int maxconns;
    int port;
    int udpport;
    char *inter;
    int verbose;
    rel_time_t oldest_live; /* ignore existing items older than this */
    uint64_t oldest_cas; /* ignore existing items with CAS values lower than this */
    int evict_to_free;
    char *socketpath;   /* path to unix socket if using local socket */
    int access;  /* access mask (a la chmod) for unix domain socket */
    double factor;          /* chunk size growth factor */
    int chunk_size;
    int num_threads;        /* number of worker (without dispatcher) libevent threads to run */
    int num_threads_per_udp; /* number of worker threads serving each udp socket */
    char prefix_delimiter;  /* character that marks a key prefix (for stats) */
    int detail_enabled;     /* nonzero if we're collecting detailed stats */
    int reqs_per_event;     /* Maximum number of io to process on each
                               io-event. */
    bool use_cas;
    enum protocol binding_protocol;
    int backlog;
    int item_size_max;        /* Maximum item size, and upper end for slabs */
    bool sasl;              /* SASL on/off */
    bool maxconns_fast;     /* Whether or not to early close connections */
    bool lru_crawler;        /* Whether or not to enable the autocrawler thread */
    bool lru_maintainer_thread; /* LRU maintainer background thread */
    bool slab_reassign;     /* Whether or not slab reassignment is allowed */
    int slab_automove;     /* Whether or not to automatically move slabs */
    int hashpower_init;     /* Starting hash power level */
    bool shutdown_command; /* allow shutdown command */
    int tail_repair_time;   /* LRU tail refcount leak repair time */
    bool flush_enabled;     /* flush_all enabled */
    char *hash_algorithm;     /* Hash algorithm in use */
    int lru_crawler_sleep;  /* Microsecond sleep between items */
    uint32_t lru_crawler_tocrawl; /* Number of items to crawl per run */
    int hot_lru_pct; /* percentage of slab space for HOT_LRU */
    int warm_lru_pct; /* percentage of slab space for WARM_LRU */
    int crawls_persleep; /* Number of LRU crawls to run before sleeping */
    bool expirezero_does_not_evict; /* exptime == 0 goes into NOEXP_LRU */
};
    settings封装了可能有的各个命令及参数。把settings定义为全局变量可在整个程序访问。

linux使用getopt解析参数的更多相关文章

  1. 使用getopt 解析参数

    getopt被用来解析命令行选项参数. #include <unistd.h> extern char *optarg; //选项的参数指针 extern int optind, //下一 ...

  2. 如何使用getopt()函数解析参数

    最近在写程序的过程中,把一部分时间都花费在程序对参数的处理上.今天听了学长说到getopt函数,才发现原来c里面还有一个专门解决参数处理的函数,查询了相关资料,这里简单总结一下. 使用int main ...

  3. Python3+getopt解析命令行参数

    一.说明 在学C语言的时候就知道可以通过argc获取命令行参数个数,可以通过argv获取具体参数.但自己写的程序获取到的参数一是没有键值形式二是写的参数不能乱序,和系统命令不太一样. 再往后点知道有g ...

  4. linux kernel的cmdline参数解析原理分析【转】

    转自:https://blog.csdn.net/skyflying2012/article/details/41142801 版权声明:本文为博主kerneler辛苦原创,未经允许不得转载. htt ...

  5. 使用getopt_long来解析参数的小函数模板

    getopt_long原型 #define no_argument 0 #define required_argument 1 #define optional_argument 2 struct o ...

  6. Linux Pthread 深入解析(转-度娘818)

    Linux Pthread 深入解析   Outline - 1.线程特点 - 2.pthread创建 - 3.pthread终止         - 4.mutex互斥量使用框架         - ...

  7. Linux Command Line 解析

    Linux Command Line 解析 0 处理模型 Linux kernel的启动包括很多组件的初始化和相关配置,这些配置参数一般是通过command line进行配置的.在进行后续分析之前,先 ...

  8. android和Linux下getopt的差别

    1. Linux下如果找不到相对应的参数,则会跳过继续找下一个 Android下如果找不到则会直接返回-1,跳出来 2. Linux下通过getopt后会把找到的元素放到数组的前面,没找到的往后移动( ...

  9. 理解 Linux backlog/somaxconn 内核参数

    https://jaminzhang.github.io/linux/understand-Linux-backlog-and-somaxconn-kernel-arguments/ 各参数的含义:h ...

随机推荐

  1. UVa 12169 (枚举+扩展欧几里得) Disgruntled Judge

    题意: 给出四个数T, a, b, x1,按公式生成序列 xi = (a*xi-1 + b) % 10001 (2 ≤ i ≤ 2T) 给出T和奇数项xi,输出偶数项xi 分析: 最简单的办法就是直接 ...

  2. UVALive 3211 Now or later(2-sat)

    2-sat问题,一种在两种可能性中选择必然关系的问题. 推荐两篇论文,也是学2-sat公认比较好的材料.前者较好理解,后者需耐心看. http://www.google.com.hk/url?sa=t ...

  3. OK335xS dhcpcd porting

    /********************************************************************** * OK335xS dhcpcd porting * 说 ...

  4. eclipse export Android jar with jni

    /*********************************************************************** * eclipse export Android ja ...

  5. hdu 2204 Eddy's爱好

    // 一个整数N,1<=N<=1000000000000000000(10^18).// 输出在在1到N之间形式如M^K的数的总数// 容斥原理// 枚举k=集合{2,3,5,7,11,1 ...

  6. 【MySQL】通过select语句把一列数据拼接成一条字符串

    通过 GROUP_CONCAT(如下图)

  7. JavaScript--事件模型(转)

    在各种浏览器中存在三种事件模型:原始事件模型( original event model),DOM2事件模型,IE事件模型.其中原始的事件模型被所有浏览器所支持,而DOM2中所定义的事件模型目前被除了 ...

  8. 利用反射自动生成SQL语句(仿Linq)

    转:http://www.cnblogs.com/the7stroke/archive/2012/04/22/2465597.html using System; using System.Colle ...

  9. 构建属于自己的ORM框架之二--IQueryable的奥秘

    上篇文章标题乱起,被吐槽了,这次学乖了. 上篇文章中介绍了如何解析Expression生成对应的SQL语句,以及IQueryable的一些概念,以及我们所搭建的框架的思想等.但还没把它们结合并应用起来 ...

  10. Party at Hali-Bula

    题意: n个人参加party,给出n个人的工作关系树,一个人和他的顶头上司不能同时参加,party达到的最大人数并判断邀请的最大人数名单是否唯一. 分析: 树状dp入门 dp[i][f],以i为根的子 ...