simple command line interface (CLI) architecture

Jun 08, 2005 2 Replies

Hello, All!



I'm trying to implement simple Command Line Interface (CLI) for our design based on linux. I will use GCC as compiler. I don't need some special features (like command line editing, commands history etc.) by now, just simple and basic functionality:


1) enter command
2) parse command line
3) execute code related to command

Seems to be simple but I don't have any idea right now, that's why I ask for you to help me out :)



With best regards, Roman Mashak. E-mail: snipped-for-privacy@tusur.ru


When you think about it, what you need is a loop (because you want to do it over and over), a read, some parsing logic and a something to do. Try that format...

while (true) { printf("Enter cmd>"); fgets(); i = parse() // for example switch( i ) { case cmd1: break; case cmd2: break; default: printf("Unknown Command\n"); } }

char *cmds[4] {"cmd1", "cmd2", "cmd3", "" };

int parse( char *str_in ) { // there are many ways to do this - mostly depending on what format the command is to take. char * parsed[20]; int parse_i = 0; char *p; int i;

p = strtok( str_in, " ," ); // parse "cmd1 arg1, arg2" do { parsed[parse_i++] = p; p = strtok( NULL, " ," ); } while ( !*p);

for ( i=0; *cmd[i], i++) { if ( strcmp ( parsed[0], cmds[i]) == 0) return i; return -1; }

When I needed a highly reliable embedded parser, I used flex and bison to generate it. It is possible to develop a bulletproof parser that can be easily extended should need arise. The initial learning curve can be steep, however.

Chris Isbell Southampton, UK

Join the Discussion

Have something to add? Share your thoughts — no account required.

Didn't find your answer?

Ask the community — no account required