c - 在C语言中处理多个命令而不是switch语句的正确方法是什么

标签 c

我有第一个程序,它通过 Linux 中的 System V 消息队列处理来自其他第二个程序的命令。

我所做的是

1-(在第二个程序中)将命令发送到 System V 消息队列

2-(在第一个程序中)从 System V 消息队列读取消息,然后将字符串格式的命令转换为整数值,以便我可以使用 switch 语句。

3-基于我调用适当函数的值。

但这太难处理每个命令了。

那么解决这个大 switch 语句的最佳方法是什么?

最佳答案

如果您有少量命令,一个简单的 if/elsif 就可以了。

enum commands cmd_num = UNKNOWN_COMMAND;

if( strcmp(cmd_string, "this") ) {
    cmd_num = THIS_COMMAND;
}
else if( strcmp(cmd_string, "that") ) {
    cmd_num = THAT_COMMAND;
}
else {
    fprintf(stderr, "Unknown command: %s", cmd_string);
}

switch(cmd_num) {
  case THIS_COMMAND:
    this();
    break;
  case THAT_COMMAND:
    that();
    break;
  default:
    fprintf(stderr, "Unknown command #%d", cmd_num);
}

但是为什么不去掉中间人呢?

if( strcmp(cmd_string, "this") ) {
    this();
elsif( strcmp(cmd_string, "that") ) {
    that();
}
else {
    fprintf("Unknown command: %s", cmd_string);
}

如果您打算有很多命令,您可以将它们放入 hash table 中以便于添加和查找。关键是命令字符串。该值可以是一个整数,带有单独的 switch 语句(或另一个哈希表)来运行命令。

或者,我们可以再次删除中间人并将其设为函数指针。

#include <stdio.h>
#include <gmodule.h>

void this() {
    puts("this");
}

void that() {
    puts("that");
}

GHashTable *init_commands() {
    return g_hash_table_new( g_str_hash, g_str_equal );
}

void add_command(GHashTable *commands, const char *command, void(*func_ptr)(void)) {
    g_hash_table_insert(commands, g_strdup(command), (void *)func_ptr);
}

void run_command(GHashTable *commands, const char *command) {
    void(*func_ptr)(void) = g_hash_table_lookup(commands, command);
    if( func_ptr ) {
        (*func_ptr)();
    }
    else {
        fprintf(stderr, "Unknown command: %s", command);
    }
}

int main() {    
    GHashTable *commands = init_commands();
    add_command(commands, "this", this);
    add_command(commands, "that", that);

    run_command(commands, "this");
}

权衡是所有命令现在必须具有相同的签名。这对于远程命令处理程序来说很常见,但需要一些时间来适应。您选择哪种方式取决于您的项目如何运作。

关于c - 在C语言中处理多个命令而不是switch语句的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59000498/

相关文章:

c - 在 C 套接字中保持客户端/服务器架构持续通信的最佳方法?

c - 在 main() 内调用 main() 是否会创建重复变量?

c - 如何在 C 中将指针转换为 double?

c++ - CUDA 函数仅适用于某些元素

c - 设置指针位置

c - C中数组的初始化

c - 变量没有正确递增

c - GtkButton 被 GtkDrawingArea 覆盖

c - fread() 没有按预期工作

c++ - 使用/NODEFAULTLIB 编译