Tuesday, April 21, 2009

Termios

So it's apparently been quite a while since my last update... So why the long break? Well... mostly because I forgot to write. Oops.

Here's a quick summary of what's happened since my last update:

  • Took a weeklong vacation to Amsterdam, Holland, with my wife. A very fun adventure, although there were some difficulties coming home. A couple couple of birthday gifts were in the carry-on instead of the checked bag, and were confiscated because they weren't allowed on the plane.
  • Finally finished stripping wallpaper and painting another room in the house. Only a bit more wallpaper left to strip, and a few more rooms to paint, and it'll be time to move on to more expensive projects.
  • My wife has decreed that we are getting a dog. Next week. She had an attack of Florence Nightingale Syndrome at the veterinary office where she works. An American Bulldog in really bad shape came in after being rescued by the local animal shelter. She decided that when he gets better, we're taking him. I met him a couple weeks later, and still am not as excited as her, but I have been wanting a dog, so hopefully everything goes well.
  • And finally, to the topic of this post: Termios.

Occasionally over the last few months, I have tried to figure out how programs like Vim and libraries like Curses and Readline are able to read and act upon individual characters from the terminal without waiting for the user to hit Enter. I tried internet searches, and even browsing the source of the NCurses library, but didn't have any luck.

Then, last night, curiosity struck again, so I made some more internet searches, and I finally hit upon the answer: Termios. If you open the man page for 'termios,' it will describe a large number of options, many of which deal with serial port settings. (In fact, I dealt with it a couple of years ago while writing a JNI serial port interface, but forgot about it shortly afterward.)

If, however, you skip the serial port settings, you will find an option under the 'c_lflag' constants named ICANON. The description is brief: "Enable canonical mode (described below)."

If you are intrigued enough to read below, you will discover that canonical mode is what determines whether characters are available immediately or queued until an end-of-line is encountered. This is exactly the option I was looking for!

So I had finally found my answer. Of course, at this point, I had completely forgotten what I really wanted to do with it when I first started searching. But I still had to play with it, so I wrote this program. It will read input in groups of up to 15 characters, outputting the groups of character codes. (Some keypresses generate multiple character codes, such as the arrow keys or the Delete key.) Press Escape to exit (that character code, 27, will be printed as well).