我想制作一个程序,以类似于 Linux 上的 ip
的方式接受命令。例如,我想要一个完整的 show interface options
命令,但用户可以只输入 show in options
或者甚至只输入 s i o
如果它们不与其他命令冲突。
我对如何解决这个问题有一些想法,我想用 C 来实现。所以问题是,在 Linux/UNIX 系统之间尽可能保持可移植性的同时,什么是解决这个问题的好方法。
我第一个想到的是有一个链表。每个列表项指向字符串数组中的下一个命令,最后一个命令具有函数调用的地址(请原谅我草率的伪代码)。
header.h
typedef int8_t (__cdecl *proc_stub)(void *data, uint16_t len);
typedef struct s_proc_stub
{
char command[16];
proc_stub proc;
struct s_proc_stub *next;
};
struct s_proc_stub proc_list[] =
{
{ "cmd", CommandFunction, ... },
{ "set", SetFunction, ... },
...
};
我觉得这可能会导致额外的 CPU 和 RAM 使用率下降。它还可能容易出错,从而导致漏洞。这个过程会面向互联网,所以我想保证代码的安全。
我的下一个想法是使用 strtok() 并对每个标记执行 strnicmp()。另一种选择是使用指针算法来更快地模拟 strtok() 而无需修改缓冲区。我觉得 strtok 是最直接的方法并且最不容易出错,但我想说我记得 strtok() 与其他两种方法相比有一些额外的开销。
它的目标平台是 Raspberry Pi,它只有大约 2GB 的 RAM 可以使用。驱动器通常很小,CPU 还可以,但不适合进行繁重的处理。我预计进程会因命令处理而承受沉重的负载,因此我想要最小化 RAM 和 CPU 使用量的理想解决方案。我很想听听一些我不知道的方法! :)
最佳答案
我认为 trie(前缀树)数据结构是合适的,https://en.wikipedia.org/wiki/Trie ;具体来说,最小化内存量,人们可能更喜欢紧凑的前缀树(基数树)。来自,https://en.wikipedia.org/wiki/Radix_tree :
In a trie, all comparisons require constant time, but it takes m comparisons to look up a string of length m. Radix trees can perform these operations with fewer comparisons, and require many fewer nodes.
关于c - Tab 完成和部分完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882854/