) Check button (implementation of the kbhit () function in Linux)

Source: Internet
Author: User
Tags vmin



People who have written MS-DOS programs usually look for functions in Linux that are equivalent to kbhit, which will detect whether a key is pressed and not actually read. Unfortunately, they did not find such a function, because there is no directly equivalent function. UNIX programmers do not notice this omission, because the Unix programming method is usually prepared for the program to wait for the event to happen. This is the common kbhit usage, so UNIX and Linux ignore it.

However, when we want to port programs from a MS-DOS, we usually need to simulate kbhit, where we can do it in informal input mode.

Test-our own kbhit

1 first, we need to define a standard header file and declare a structure for the terminal settings. Peek_character is used to test whether a key is pressed. Then we define the prototype of the function we will use.

# Include <stdio. h>
# Include <termios. h>
# Include <term. h>
# Include <curses. h>
# Include <unistd. h>
Static struct termios initial_settings, new_settings;
Static int peek_character =-1;
Void init_keyboard ();
Void close_keyboard ();
Int kbhit ();
Int readch ();

2. The main function calls the init_keyboard function to configure the terminal, and then repeats once a second to call the kbhit function. If the key check is Q, the close_keyboard function returns normal behavior and exits the program.

Int main ()
Int CH = 0;
Init_keyboard ();
While (Ch! = 'Q '){
Printf ("looping \ n ");
Sleep (1 );
If (kbhit ()){
Ch = readch ();
Printf ("You hit % C \ n", CH );
Close_keyboard ();
Exit (0 );

3 init_keyboard and close_keyboard configure the terminal at the beginning and end of the program.

Void init_keyboard ()
Tcgetattr (0, & initial_settings );
New_settings = initial_settings;
New_settings.c_lflag & = ~ Icanon;
New_settings.c_lflag & = ~ Echo;
New_settings.c_lflag & = ~ Isig;
New_settings.c_cc [Vmin] = 1;
New_settings.c_cc [vtime] = 0;
Tcsetattr (0, tcsanow, & new_settings );
Void close_keyboard ()
Tcsetattr (0, tcsanow, & initial_settings );

4. The function for checking the keyboard buttons is as follows:

Int kbhit ()
Char ch;
Int nread;
If (peek_character! =-1)
Return 1;
New_settings.c_cc [Vmin] = 0;
Tcsetattr (0, tcsanow, & new_settings );
Nread = read (0, & Ch, 1 );
New_settings.c_cc [Vmin] = 1;
Tcsetattr (0, tcsanow, & new_settings );
If (nread = 1 ){
Peek_character = CH;
Return 1;
Return 0;

5. Press the button to read from the next function, readch, and set peek_character to-1 for the next loop.

Int readch ()
Char ch;
If (peek_character! =-1 ){
Ch = peek_character;
Peek_character =-1;
Return ch;
Read (0, & Ch, 1 );
Return ch;

When we run this program, we will get the following output:

You hit H
You hit d
You hit Q

Working Principle

In init_keyboard, configure the terminal to read one character before returning (min = 1, time = 0. Kbhit changes it to the detection input and returns immediately (min = 0, time = 0), and then restores the original settings before the program exits.

Note: we must read the pressed key, but it is stored locally, so that we can return it as needed.

Virtual console

Linux provides a feature called virtual console. Many terminal devices are available. All devices share the screen, keyboard, and mouse of the PC. Generally, 12 such virtual consoles are installed and configured in a Linux system.

The virtual console is accessed through the character device/dev/ttyn, where n is a number starting from 1.

If we use text to log on to Linux, we will receive a logon prompt when Linux is started. Then we can use the user name and password to log on. The device we use is the first virtual console, the terminal device/dev/tty1.

Using the WHO and PS commands, we can see the login users, shell and the programs that are running on this virtual console:

$ Who
Neil tty1 Mar 8
$ PS-e
PID tty time cmd
1092 tty1 00:00:00 Login
1414 tty1 00:00:00 bash
1431 tty1 00:00:00 Emacs

Here we can see that the login user is Neil and runs Emacs on the console device/dev/tty1.

In Linux, a Getty process is usually started to run on the first six virtual consoles, so that the same screen can be used and the keyboard and mouse can be logged on six times. We can use PS to see these processes:

$ PS-e
PID tty time cmd
1092 tty1 00:00:00 Login
1093 tty2 00:00:00 mingetty
1094 tty3 00:00:00 mingetty
1095 tty4 00:00:00 mingetty
1096 tty5 00:00:00 mingetty
1097 tty6 00:00:00 mingetty

Here we can see that the default SuSE Getty program, mingetty, runs on the other five virtual consoles and waits for the user to log on.

We can use a special key combination CTRL + ALT + F <n> to switch between the virtual console. Here N is the virtual console number we want to switch. To switch to the 2nd virtual console, press Alt + Ctrl + F2, and CTRL + ALT + F1 will return to the first console. (The CTRL + F <n> combination can also take effect when character login rather than graphic login switching)

If Linux starts a graphical login, either through startx or through a display manager, such as xdm, the X Window System will start the login using the first idle virtual console, usually/dev/tty7. When using the X Window System, we can use CTRL + ALT + F <n> to switch to the text console, and use CTRL + ALT + F7 to return to the graphic console.

Generally, multiple alive jobs run on Linux. If we do this, for example, use the command

$ Startx-: 1

Linux will start X server on the next idle virtual console. In this case, it is usually/dev/tty8, then we can use CTRL + ALT + F8 and CTRL + ALT + F7 to switch between them.

In all other respects, the behavior of the virtual console is similar to that of the terminal, as described in this chapter. If a process has the correct permissions, the virtual console can perform operations such as opening, reading, and writing in the same way as the usual terminal.

Pseudo Terminal

Unix-like systems, including Linux, have the characteristics of a Pseudo Terminal. These devices act like the terminals we use in this chapter. what is different is that they do not have hardware associated with them. They can be used to provide a class Terminal interface for other programs.

For example, using two pseudo terminals allows two chess programs to fight each other, although the program itself is set to interact with people on the terminal. A program that acts as an intermediary transmits the action of one program to another. The Pseudo Terminal can make the program run as usual without providing a terminal.

Pseudo terminals were previously implemented in a specific system. Now they have entered the unix98 pseudo-final or Pty standard of the single UNIX specification.


In this chapter, we understand three different aspects of the control terminal. In the first part of this chapter, we learned about redirection detection and how to interact with a terminal, even though the standard file descriptor has been redirected. The hardware model we discuss and its history. Then we learned about General terminal interfaces and the termios structure that provides detailed control on Linux terminal processing. We also saw how to use the termios database and functions related to screen management in a terminal-independent manner. We also learned how to detect buttons immediately. Finally, we discuss the Linux virtual console and Pseudo Terminal.


In addition:

Is there a function similar to bioskey (0) for how to handle keyboard response in Linux?


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.