简体   繁体   English

C:将命令行arg映射到编译时常量

[英]C: map a command-line arg to a compile-time constant

I'm writing a C program that accepts a system resource name (eg RLIMIT_NOFILE ) and prints some resource limit info for it. 我正在编写一个接受系统资源名称(例如RLIMIT_NOFILE )并为其打印一些资源限制信息的C程序。

The resource constants are defined in <sys/resource.h> , eg 资源常量在<sys/resource.h>中定义,例如

#define RLIMIT_NOFILE   5

I'm looking for a good way to map the command-line argument (eg RLIMIT_NOFILE ) to the corresponding numeric value (eg 5). 我正在寻找一种将命令行参数(例如RLIMIT_NOFILE )映射到相应数值(例如5)的好方法。

I originally planned to do something like: 我最初打算做类似的事情:

int resource = -1;
char *resource_names[] = {
    "RLIMIT_NOFILE", "RLIMIT_NPROC", "RLIMIT_RSS"
};

for (i = 0; i < sizeof(resource_names)/sizeof(char *); i++) {
    if (strcmp(argv[1], resource_names[i]) == 0) {
        resource = eval(resource_names[i]);
        break;
    }
}

But C doesn't seem to have anything like eval , and even if it did, the compile-time constants wouldn't be available at run-time. 但是C似乎没有eval东西,即使这样做,编译时常量在运行时也不可用。

For now, I'm doing the following, but I'm curious if there's a better approach. 现在,我正在做以下事情,但是我很好奇是否有更好的方法。

#include <stdio.h>
#include <string.h>
#include <sys/resource.h>

int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("Usage: %s <resource>\n", argv[0]);
        return 1;
    }

    char *resource_names[] = {
        "RLIMIT_NOFILE", "RLIMIT_NPROC", "RLIMIT_RSS"
    };
    int resources[] = {
        RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS
    };
    int i, resource = -1;

    for (i = 0; i < sizeof(resources)/sizeof(int); i++) {
        if (strcmp(argv[1], resource_names[i]) == 0) {
            resource = resources[i];
            break;
        }
    }
    if (resource == -1) {
        printf("Invalid resource.\n");
        return 1;
    }

    struct rlimit rlim;
    getrlimit(resource, &rlim);
    printf("%s: %ld / %ld\n", argv[1], rlim.rlim_cur, rlim.rlim_max);

    return 0;
}

The RLIMIT_x constants are all low-value integers that can be used as indexes into an array, or (for your problem) use an array to find the index and it will correspond to the value you want. RLIMIT_x常量都是可以用作数组索引的所有低值整数, 或者 (针对您的问题)使用数组来查找索引,并且该索引将与所需的值相对应。

Or you could have an array of structures, containing both the value and the string. 或者,您可以有一个结构数组,同时包含值和字符串。 Something like 就像是

static const struct
{
    int limit;
    char *name;
} rlimits[] = {
    { RLIMIT_NOFILE, "RLIMIT_NOFILE" },
    { RLIMIT_NPROC, "RLIMIT_NPROC" },
    // Etc.
};

Then it's easy to iterate over the array and "map" a string to a value (or do the opposite). 然后,很容易遍历数组并将字符串“映射”到值(或相反)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM