我有第一个程序通过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");
}
权衡是,所有命令现在必须具有相同的签名。这对于远程命令处理程序很常见,但是需要一些时间来习惯。选择哪种方式取决于项目的工作方式。