Page 1 of 1

CLI Input

Posted: Sat Sep 10, 2011 5:56 pm
by mark3094
Hi,

Just thinking about a CLI, and getting input to it from the keyboard.
I already have a basic keyboard driver using interrupts (x86 arch) which simply prints characters to the screen.

Is scanf the best function for reading the input, or is a custom function better?


Thankyou

Re: CLI Input

Posted: Sat Sep 10, 2011 6:31 pm
by Chandra
Scanf is better if you need to deal with formatted inputs. That's for sure.

Re: CLI Input

Posted: Sat Sep 10, 2011 6:43 pm
by mark3094
I really only need to get a string I guess...

I suppose I don't need to use scanf (in a way I'm hoping not to, because then I will need to write the scanf function)
I should just be able to get the keyboard input somehow.

How do most people do it?

Re: CLI Input

Posted: Sat Sep 10, 2011 7:35 pm
by pcmattman
Usually you have the keyboard interrupt add keys to a ring buffer and exit immediately.

Keys can then be taken from the ring buffer at any time (not dependent on interrupts) by the kernel or by some abstraction layer for your userspace programs.

Re: CLI Input

Posted: Sat Sep 10, 2011 7:55 pm
by mark3094
pcmattman wrote:Usually you have the keyboard interrupt add keys to a ring buffer and exit immediately.

Keys can then be taken from the ring buffer at any time (not dependent on interrupts) by the kernel or by some abstraction layer for your userspace programs.
Thanks. This sounds perfect. So far I have the interrupt putting the key into a static pointer. Seems to work well so far.
Now just to figure out how to effectively parse the buffer :)

Thanks everyone

Re: CLI Input

Posted: Mon Sep 12, 2011 2:24 am
by Solar
I discourage use of scanf(). That function is no good for "parsing" anything that hasn't been written by the very same program, because of its dismal handling in case of malformed input. (I.e., if you write whitespace-seperated numbers with printf(), then scanf() is the perfect counterpart for reading them back, but if you want to receive user input, scanf() sucks in spades.)

I recommend reading the input via fgets() (or similar), and then parsing it yourself (using e.g. strtok() for tokenizing, and then parsing the tokens manually). That way, you get much better error handling, and can even print meaningful error messages...

Re: CLI Input

Posted: Mon Sep 12, 2011 2:34 am
by piranha
For a CLI, you're really just reading in strings and parsing it according to the rules of your shell, so scanf wouldn't be the thing to use. The most basic thing to need to parse is "<program-name> [arg1] [arg2]", which can easily be done. Then you might want to add things like arguments with spaces, variables or whatever, etc. But that all needs to be parsed according to whatever standard you create, so you need to write the parser yourself. This is not hard, and can be done with a couple of simple functions to get basic functionality.

-JL