Linux下應用程式可能需要互動式輸入指令,但普通的标準IO進行指令輸入顯得有些呆闆,人性化不足。本文講述使用libreadline庫,實作類似sh的交換終端:支援指令自動補全,支援曆史指令等。
part1: readline安裝
(1) 下載下傳readline源碼:http://download.chinaunix.net/download/0009000/8886.shtml
(2) 解壓後, 在源碼目錄依次執行 ./configure, make, sudo make install 完成安裝
part2:readline使用舉例
#include <stdlib.h>
#include <stdio.h> //注意,readline.h中可能需要調用标準IO庫的内容,是以stdio.h必須在readline.h之前被包含
#include <readline/readline.h>
#include <readline/history.h>
/*
* 真正的指令執行函數
* 測試時,被定義為樁函數了
*/
int com_list(char *para);
int com_view(char *para);
int com_rename(char *para);
int com_stat(char *para);
int com_pwd(char *para);
int com_delete(char *para);
int com_help(char *para);
int com_cd(char *para);
int com_quit(char *para);
/*
* A structure which contains information on the commands this program
* can understand.
*/
typedef struct
{
char *name; /* User printable name of the function. */
rl_icpfunc_t *func; /* Function to call to do the job. */
char *doc; /* Documentation for this function. */
} COMMAND;
COMMAND commands[] =
{
{"cd", com_cd, "Change to directory DIR"},
{"delete", com_delete, "Delete FILE"},
{"help", com_help, "Display this text"},
{"?", com_help, "Synonym for `help'"},
{"list", com_list, "List files in DIR"},
{"ls", com_list, "Synonym for `list'"},
{"pwd", com_pwd, "Print the current working directory"},
{"quit", com_quit, "Quit using Fileman"},
{"rename", com_rename, "Rename FILE to NEWNAME"},
{"stat", com_stat, "Print out statistics on FILE"},
{"view", com_view, "View the contents of FILE"},
{(char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL}
};
int com_list(char *para)
{
printf("do com_list:%s\n", para);
///> add @2020.05.29
for (unsigned char index = 0x00; index < sizeof(commands)/sizeof(COMMAND); index++)
{
printf("Test cli cmd doc is %s\r\n", commands[index].doc);
}
return 0;
}
int com_view(char *para)
{
printf("do com_view:%s\n", para);
return 0;
}
int com_rename(char *para)
{
printf("do com_rename:%s\n", para);
return 0;
}
int com_stat(char *para)
{
printf("do com_stat:%s\n", para);
return 0;
}
int com_pwd(char *para)
{
printf("do com_pwd:%s\n", para);
return 0;
}
int com_delete(char *para)
{
printf("do com_delete:%s\n", para);
return 0;
}
int com_help(char *para)
{
printf("do com_help:%s\n", para);
return 0;
}
int com_cd(char *para)
{
printf("do com_cd:%s\n", para);
return 0;
}
int com_quit(char *para)
{
printf("do com_quit:%s\n", para);
exit(0);
}
char *dupstr(char *s)
{
char *r;
r = malloc(strlen(s) + 1);
strcpy(r, s);
return (r);
}
// clear up white spaces
char *stripwhite(char *string)
{
register char *s, *t;
for (s = string; whitespace(*s); s++)
;
if (*s == 0)
return (s);
t = s + strlen(s) - 1;
while (t > s && whitespace(*t))
t--;
*++t = '\0';
return s;
}
/*
* Look up NAME as the name of a command, and return a pointer to that
* command. Return a NULL pointer if NAME isn't a command name.
*/
COMMAND *find_command(char *name)
{
register int i;
for (i = 0; commands[i].name; i++)
if (strcmp(name, commands[i].name) == 0)
return (&commands[i]);
return ((COMMAND *)NULL);
}
/* Execute a command line. */
int execute_line(char *line)
{
register int i;
COMMAND *command;
char *word;
/* Isolate the command word. */
i = 0;
while (line[i] && whitespace(line[i]))
i++;
word = line + i;
while (line[i] && !whitespace(line[i]))
i++;
if (line[i])
line[i++] = '\0';
command = find_command(word);
if (!command)
{
fprintf(stderr, "%s: No such command for Hytera Cli Framework.\n", word);
return (-1);
}
/* Get argument to command, if any. */
while (whitespace(line[i]))
i++;
word = line + i;
/* Call the function. */
return ((*(command->func))(word));
}
/*
* Generator function for command completion. STATE lets us know whether
* to start from scratch; without any state (i.e. STATE == 0), then we
* start at the top of the list.
*/
char *command_generator(const char *text, int state)
{
static int list_index, len;
char *name;
/*
* If this is a new word to complete, initialize now. This includes
* saving the length of TEXT for efficiency, and initializing the index
* variable to 0.
*/
if (!state)
{
list_index = 0;
len = strlen(text);
}
/* Return the next name which partially matches from the command list. */
while (name = commands[list_index].name)
{
list_index++;
if (strncmp(name, text, len) == 0)
return (dupstr(name));
}
/* If no names matched, then return NULL. */
return ((char *)NULL);
}
/*
* Attempt to complete on the contents of TEXT. START and END bound the
* region of rl_line_buffer that contains the word to complete. TEXT is
* the word to complete. We can use the entire contents of rl_line_buffer
* in case we want to do some simple parsing. Return the array of matches,
* or NULL if there aren't any.
*/
char **fileman_completion(const char *text, int start, int end)
{
char **matches;
matches = (char **)NULL;
/*
* If this word is at the start of the line, then it is a command
* to complete. Otherwise it is the name of a file in the current
* directory.
*/
if (start == 0)
matches = rl_completion_matches(text, command_generator);
return (matches);
}
/*
* Tell the GNU Readline library how to complete. We want to try to complete
* on command names if this is the first word in the line, or on filenames
* if not.
*/
void initialize_readline()
{
/* Allow conditional parsing of the ~/.inputrc file. */
rl_readline_name = ">";
/* Tell the completer that we want a crack first. */
rl_attempted_completion_function = fileman_completion;
}
int main(int argc, char **argv)
{
char *line, *s;
initialize_readline(); /* Bind our completer. */
/* Loop reading and executing lines until the user quits. */
for (;;)
{
line = readline("[Cli Framework]$ ");
if (!line)
break;
/*
* Remove leading and trailing whitespace from the line.
* Then, if there is anything left, add it to the history list
* and execute it.
*/
s = stripwhite(line);
if (*s)
{
add_history(s);
execute_line(s);
}
free(line);
}
exit(0);
}
注意,編譯的時候需要連接配接readline庫,例如:
gcc -o readline_test readline_test.c -lreadline -std=c99
part3: readline下的IO複用
但是如果我們有多個 IO 要處理,比如既要從一個網絡 IO 中讀資料,又要從标準輸入中讀取指令,上面的方法就不合适了。為了解決這個問題,我們需要自己用 select 函數監控這兩個 IO,當它們可讀的時候通知這兩個子產品中的輸入函數。形象地說,就是把資料“喂給”這兩個子產品。這樣的模式需要 readline 提供“被動喂給”的工作方式。這種工作方式在 readline 中已有實作。首先,我們需要往 readline 注冊回調函數,當 readline 讀取到一行後,這個回調函數将被調用:
rl_callback_handler_install ("prompt> ", handle_command);
接下去,在主事件循環中,我們需要調用 rl_callback_read_char() 通知 readline 去讀取一個字元。下面給一個例子:
static void handle_command (char *line)
{
...
}
int
main (int argc, char **argv)
{
int netfd
fd_set allfd;
int maxfd;
netfd = connect_to_server ();
FD_ZERO (&allfd);
FD_SET (fileno(stdin), &allfd);
FD_SET (netfd, &allfd);
maxfd = netfd;
rl_callback_handler_install ("ccnet> ", handle_command);
while (1) {
fd_set rfds;
int retval;
rfds = allfd;
retval = select (maxfd + 1, &rfds, NULL, NULL, NULL);
if (retval < 0)
perror ("select");
if (FD_ISSET(0, &rfds))
rl_callback_read_char();
if (FD_ISSET(netfd, &rfds))
read_from_network (netfd);
}
}
關于readline更多的使用請自行閱讀readline的man檔案。