Taking up/down arrow as input to a program in Unix

2019-08-29 01:55发布

问题:

I am implementing my own shell. But to supprt for command history, I need to use monitor up/down arrow key as in standard shells. Please tell me how to handle arrow keys as input or does these keys generate signals? Please elaborate.

回答1:

Arrows and other special keys send you special strings that depend on the terminal being used or emulated. To deal with this most simply, you could use a library such as termcap. Even simpler, given your stated purpose (command history support), would be to use readline, which basically does it for you (and lets the user customize aspects of their preferred mode of working across the many applications that link to the same library).



回答2:

It depends on how gnarly you're expected to go. Worse case, you're writing the keyboard interrupt handler. Best case, something like readline.

Check with your prof for direction here. Also check your course materials to see if the prof has given links/examples regarding this.



回答3:

Does the assignment specifically say you need to have a "cursor key driven" command history?

Simple option is to mimic the shells fc e.g.

$ ls
... file listing ...
$ fc -l
1 ls
2 fc -l
$ fc -r 1
... file listing ...

and (while I'm presenting established ideas as my own, might as well go all the way) to be able to edit the command line you could use

fc -e start end

to write the history from start to end into a file, launch an editor and then execute the resulting file as a script. This way your shell is not using a library, but launching commands and executing scripts, which is what shells are supposed to do anyway.



标签: unix shell