I don't think you can get a "real signal from the keyboard"
directly in a normal
user-space program. Whether you are programming in C/C++ or in Assembler language doesn't make a difference in this regard. I think you would have to write a
kernel-module and load it into the Linux kernel in order to get this kind of "low-level" hardware access. But that would require a deep understanding of kernel hacking and the hardware.
(and, of course, it would be very hardware-specific and non-portable)
Fortunately, the Linux kernel already provides an user-space interface to the keyboard, as a device file:
/dev/input/by-path/<youir_name_here>-kbd
Minimal example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/input.h>
#define KEYMAP_SIZE ((KEY_MAX / 8) + 1)
int main()
{
char key_map[KEYMAP_SIZE];
FILE *kbd = fopen("/dev/input/by-path/platform-i8042-serio-0-event-kbd", "r");
if (!kbd)
{
fputs("Error Failed to open keyboard device!\n", stderr);
return EXIT_FAILURE;
}
for (;;)
{
memset(key_map, 0, sizeof(key_map));
ioctl(fileno(kbd), EVIOCGKEY(sizeof(key_map)), key_map);
for (size_t i = 0; i < KEYMAP_SIZE; ++i)
{
printf("%02X", key_map[i]);
}
puts("\n");
usleep(100000);
}
return EXIT_SUCCESS;
}
| |
Above code dumps the current state of all keys (including Shift, Ctrl and Alt), in regular intervals. If you are interested in a specific key, then you just need to extract the proper bit from the
key_map array.
Note: You may need to run this with
sudo
, otherwise permission to the keyboard device may be denied.