Yusuf Ak
Yusuf Ak

Reputation: 781

Implementing commands history triggered by arrow up/down keys in C

I have implemented my own shell which executes all existing UNIX commands and several custom commands. What I need to do is, to access previous commands by using arrow up/down keys in the way exactly how UNIX terminal does.

I have found that I could use getch() method of <curses.h> library. Even if I couldn't figure out how to use that method to expect non-blocking keyboard input, the real problem with that is that I need to compile the program to be able use it as following: gcc myShell.c -lcurses

What I have to do is probably using a signal to listen background input without expecting Enter input. I have also tried to fork() to create another process which will be responsible of waiting arrow keys inputs and then used getch() method to be able to catch the key but it didn't work either.

Since I already use read() method to read the command line inserted by the user. This arrow key input should be completely independent from the existing input reading.

Some answers in Stackoverflow points the <conio.h> library which does not exist in UNIX, hence unfortunately platform dependent.

To summarize briefly, I need to read arrow up/down keys in the background in my own shell and I have to do that platform independent and without being have to type something other than gcc myShell.c for compilation. It also should be captured without Enter press.

If any details about my question is not clear enough, please let me know to explain with more details as I could.

Thanks in advance!

Upvotes: 2

Views: 3021

Answers (1)

Tim Sweet
Tim Sweet

Reputation: 645

The problem here is with the terminal you're using, not your program. For example, Windows command prompt will buffer input before even sending it to your program, so there is no platform-independent way to force the terminal to give you that data. I suspect curses has a platform-dependent way to turn off that buffering, and thus can get the character.

See answers to this question for more details: How to avoid press enter with any getchar()

Upvotes: 2

Related Questions