What I am trying to do
So, I have been trying to access keyboard input in Linux. Specifically, I need to be able to access modifier key presses without other keys being pressed. Furthermore, I want to be able to do this without an X system running.
So, in short, my requirements are these:
Works on Linux
Does not need X11
Can retrieve modifier key press without any other keys being pressed
This includes the following keys:
Shift
Control
Alt
All I need is a simple 0 = not pressed, 1 = currently pressed to let me know if
the key is being held down when the keyboard is checked
My computer setup
My normal Linux machine is on a truck towards my new apartment; so, I only have a Macbook Air to work with right now. Therefore, I am running Linux in a VM to test this out.
Virtual Machine in VirtualBox
OS: Linux Mint 16
Desktop Environment: XFCE
Everything below was done in this environment. I've tried both with X running and in one of the other ttys.
My Thoughts
I'll alter this if someone can correct me.
I've done a fair bit of reading to realize that higher-level libraries do not provide this kind of functionality. Modifier keys are used with other keys to provide an alternate key code. Accessing the modifier keys themselves through a high-level library in Linux isn't as easy. Or, rather, I haven't found a high-level API for this on Linux.
I thought libtermkey would be the answer, but it doesn't seem to support the Shift modifier key any better than normal keystroke retrieval. I'm also not sure if it works without X.
While working with libtermkey (before I realized it didn't get shift in cases like Shift-Return), I was planning to write a daemon that would run to gather keyboard events. Running copies of the daemon program would simply pipe requests for keyboard data and receive keyboard data in response. I could use this setup to have something always running in the background, in case I cannot check key code statuses at specific times (have to be receive key codes as they happen).
Below are my two attempts to write a program that can read from the Linux keyboard device. I've also included my small check to make sure I had the right device.
Attempt #1
I have tried to access the keyboard device directly, but am encountering issues. I have tried the suggestion here that is in another Stack Overflow thread. It gave me a segmentation fault; so, I changed it from fopen to open:
// ...
int fd;
fd = open("/dev/input/by-path/platform-i8042-serio-0-event-kbd", O_RDONLY);
char key_map[KEY_MAX/8 + 1];
memset(key_map, 0, sizeof(key_map));
ioctl(fd, EVIOCGKEY(sizeof key_map), key_map);
// ...
While there was no segmentation fault, there was no indicator of any key press (not just modifier keys). I tested this using:
./foo && echo "TRUE" || echo "FALSE"
I've used that to test for successful return codes from commands quite a lot; so, I know that's fine. I've also outputted the key (always 0) and mask (0100) to check. It just doesn't seem to detect anything.
Attempt #2
From here, I thought I'd try a slightly different approach. I wanted to figure out what I was doing wrong. Following this page providing a snippet demonstrating printing out key codes, I bundled that into a program:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <linux/input.h>
int main(int argc, char** argv) {
uint8_t keys[128];
int fd;
fd = open("/dev/input/by-path/platform-i8042-serio-event-kbd", O_RDONLY);
for (;;) {
memset(keys, 0, 128);
ioctl (fd, EVIOCGKEY(sizeof keys), keys);
int i, j;
for (i = 0; i < sizeof keys; i++)
for (j = 0; j < 8; j++)
if (keys[i] & (1 << j))
printf ("key code %d\n", (i*8) + j);
}
return 0;
}
Previously, I had the size to 16 bytes instead of 128 bytes. I should honestly spend a bit more time understanding ioctl and EVIOCGKEY. I just know that it supposedly maps bits to specific keys to indicate presses, or something like that (correct me if I'm wrong, please!).
I also didn't have a loop initially and would just hold down various keys to see if a key code appeared. I received nothing; so, I thought a loop might make the check easier to test in case a missed something.
How I know the input device is the right one
I tested it by running cat on the input device. Specifically:
$ sudo cat /dev/input/by-path/platform-i8042-serio-0-event-kbd
Garbage ASCII was sent to my terminal on key press and release events starting with the return (enter) key when I began the output using cat. I also know that this seems to work fine with modifier keys like shift, control, function, and even Apple's command key on my Macbook running a Linux VM. Output appeared when a key was pressed, began to appear rapidly from subsequent signals sent by holding the key down, and outputted more data when a key was released.
So, while my approach may not be the right one (I'm willing to hear any alternative), the device seems to provide what I need.
Furthermore, I know that this device is just a link pointing to /dev/input/event2 from running:
$ ls -l /dev/input/by-path/platform-i8042-serio-0-event-kbd
I've tried both programs above with /dev/input/event2 and received no data. Running cat on /dev/input/event2 provided the same output as with the link.
Open the input device,
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <string.h>
#include <stdio.h>
static const char *const evval[3] = {
"RELEASED",
"PRESSED ",
"REPEATED"
};
int main(void)
{
const char *dev = "/dev/input/by-path/platform-i8042-serio-0-event-kbd";
struct input_event ev;
ssize_t n;
int fd;
fd = open(dev, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Cannot open %s: %s.\n", dev, strerror(errno));
return EXIT_FAILURE;
}
and then read keyboard events from the device:
while (1) {
n = read(fd, &ev, sizeof ev);
if (n == (ssize_t)-1) {
if (errno == EINTR)
continue;
else
break;
} else
if (n != sizeof ev) {
errno = EIO;
break;
}
The above snippet breaks out from the loop if any error occurs, or if the userspace receives only a partial event structure (which should not happen, but might in some future/buggy kernels). You might wish to use a more robust read loop; I personally would be satisfied by replacing the last break with continue, so that partial event structures are ignored.
You can then examine the ev event structure to see what occurred, and finish the program:
if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2)
printf("%s 0x%04x (%d)\n", evval[ev.value], (int)ev.code, (int)ev.code);
}
fflush(stdout);
fprintf(stderr, "%s.\n", strerror(errno));
return EXIT_FAILURE;
}
For a keypress,
ev.time: time of the event (struct timeval type)
ev.type: EV_KEY
ev.code: KEY_*, key identifier; see complete list in /usr/include/linux/input.h
ev.value: 0 if key release, 1 if key press, 2 if autorepeat keypress
See Documentation/input/input.txt in the Linux kernel sources for further details.
The named constants in /usr/include/linux/input.h are quite stable, because it is a kernel-userspace interface, and the kernel developers try very hard to maintain compatibility. (That is, you can expect there to be new codes every now and then, but existing codes rarely change.)
Related
I am redirecting the ncurses hmi to a different, already existing terminal. While the output part works fine (and is therefore not shown here), the input misses keys which then appear in the terminal as though they had been entered without ncurses.
#include <stdio.h>
#include <curses.h>
int main(int argc, char *argv[])
{
FILE *fd = fopen(argv[1], "r+");
SCREEN *scr = newterm(nullptr, fd, fd);
set_term(scr);
noecho();
keypad(stdscr, TRUE);
while (true) {
int ch = wgetch(stdscr);
printf("In %d\r\n", ch);
}
return 0;
}
I create two terminals on Ubuntu and get the name of one (let's call it the 'curses-terminal') using 'tty'. This name is then used as argument when starting the above in the other terminal.
When typing in the curses-terminal, I expect the codes of the keys to appear in the other terminal without seeing anything in the curses-terminal.
Instead, I see some of the characters diffuse into the curses-terminal without their code being displayed in the other one. This happens with normal characters when typing more quickly, but it happens especially with arrow keys and ALT- combinations, where the error rate is >> 50%.
Are there any settings which I have forgotten?
Using G.M.'s hint, I was able to reliably get all input.
Run
tail -f /dev/null
in the curses-terminal before attaching the ncurses app.
Should you be tempted (like me) though to send this command from within your app after fopen, you may end up frustrated.
I'm trying to implement a solution in pure C to monitor new entries made to log file that records a high volume of requests to a web service.
I would like something like tail -f, where a change in the log file results in my process getting the new changes instantly.
This needs to run on Solaris 10, unfortunately.
I know this question has been asked and answered in other threads, but none of the solutions acceptable for my situation
1) The solution must not require super user access in any way. As this is a enterprise production environment, no superuser access is available to me on this system, so I can't do something like install a driver.
2) The log file will be very large. Parsing it entirely, repeatedly for new changes is not acceptable.
It seems to me that if I can run tail -f as a non-privileged user, I should be able to do the same programmatically as the same user. I realize a nice hack would be to pipe the output from tail -f into my process, though I would like something cleaner.
This is very straightforward - just read, and if you read zero bytes, wait for a specified time. Just for illustration (open your own files and improve buffer and error handling to taste). I have edited this to show where error handling and seeking the last lines should occur, and fixed the position of the sleep(). This is by no means a complete example, just an indication of how things could be done.
#include <unistd.h>
#include <stdio.h>
#define NBUF 1024
int main()
{
char buf[NBUF];
ssize_t rcount, wcount;
int fin = 0, fout = 1; /* Or use open. */
/* Code to display the last 10 lines goes here. */
while (1)
{
while ((rcount = read (fin, buf, NBUF)) > 0)
{
wcount = write (fout, buf, rcount);
if (wcount != rcount)
{
perror("write didn't work.");
/* Handle error here, exit() or whatever. */
}
}
if (rcount == -1)
{
perror("Read didn_t work...");
/* Handle error here, exit() or something else. */
sleep (1);
}
}
I need a command in cmd that works like pause but I can code to continue.
e.g.
system("pause");
some lines of code;`
The problem with system("pause") is that "some lines of code" will not work until the user press sth.
I want to continue cmd with some command.
I want something that run the code but update cmd only when I give the
permission to it.
If I understand correctly, the code shall produce output which you don't want to be shown before you press a key. If you don't mind to have the output paged, you could use something like
FILE *stream = popen("PAUSE<CON&&MORE", "w");
and let the code output to stream (with fprintf(stream, ...) etc.).
Don't ever use system() if you can avoid it. It's crude, error-prone, and non-portable.
C11 introduces threading support, including thrd_sleep(). That should be your preferred solution (if supported by your compiler setup).
If your compiler vendor does not support C11, bugger him about it. That standard is almost four years old now.
WinAPI defines the Sleep() function:
VOID WINAPI Sleep(
_In_ DWORD dwMilliseconds
);
This function causes a thread to relinquish the remainder of its time
slice and become unrunnable for an interval based on the value of
dwMilliseconds.
#include <windows.h>
int main()
{
Sleep( 5000 ); // pause execution for at least 5 seconds
some_lines_of_code;
return 0;
}
I think what you're looking for is a method to check if stdin contains data ready to read; you want to use some non-blocking or asynchronous I/O so that you can read input when it becomes available, and perform other tasks until then.
You won't find a whole heap about non-blocking/asynchronous I/O in standard C, but in POSIX C you can set STDIN_FILENO as non-blocking using fcntl. As an example, here's a program which prompts you to press enter (like pause does) and busy-loops, allowing your code to conduct other (preferably non-blocking) actions inside the loop while it waits for the keystroke (ahemm, byte, since stdin is technically a file):
#include <stdio.h>
#include <fcntl.h>
int main(void) {
char c;
puts("Press any key to continue...");
fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK);
while (read(STDIN_FILENO, 1, &c) != 1 && errno == EAGAIN) {
/* code in here will execute repeatedly until a key is struck or a byte is sent */
errno = 0;
}
if (errno) {
/* code down here will execute when an input error occurs */
}
else {
/* code down here will execute when that precious byte is finally sent */
}
}
That's non-blocking I/O. Other alternatives include using asynchronous I/O or extra threads. You should probably use non-blocking I/O or asynchronous I/O (i.e. epoll or kqueue) for this task in particular; using extra threads just to determine when a character is sent to stdin is likely a little bit too hefty.
Just trying to seek to understand. I'm writing a small program that will read in a keystroke event from the keyboard, and trigger certain events (using a switch statement). I'm making some assumptions, and attempting to treat the keyboard like a txt file to read from.
I'm kind of at a loss as to the simplest way to do this.
What i WANT to do it open the file(keyboard event4), and use something like fgets to read it in character by character in an infinite while loop, then use a switch statement to break out of the loop and exit.
Where i'm getting stuck is the fact that these are system calls, and i'm basically unsure how to handle them.
The code below definitely won't compile, just putting it there as a rough demonstration of what i am trying to do.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
// errors on opening
int fd = open("/dev/input/event4", O_RDONLY);
if(fd < 0)
{
printf("error while opening/n");
return 1;
}
int keystroke = 0;
while (1)
{
keystroke = fgetsc(fd);
switch(keystroke)
{
case '1' :
break;
case '2' :
break;
case '3' :
break;
default:
printf("waiting for 1, 2, 3/n");
}
close(fd);
return 0;
}
1) Read "raw keyboard input" is generally OS-dependent. The APIs and techniques can vary greatly depending if you're on Windows vs Linux, for example.
2) It sounds like you're on a *nix variant (Linux or MacOS, for example). If you want to do all the "grunge" yourself, here's a great "howto":
http://www.tldp.org/HOWTO/pdf/Keyboard-and-Console-HOWTO.pdf
3) You'll need to put the keyboard device into "raw", "unbuffered" mode in order to read keystrokes. Among other things...
4) I would encourage you, however, to leverage a higher-level library, like ncurses or SDL.
'Hope that helps!
In my C program I would like to know where my cursor is located in terminal. For example, another program could have written something before mine and I would like to know how much space is left before the last column of the terminal, or I could not know the terminal reaction to some special sequences (like colors: I could write it but they are not showed).
Any suggestion?
Edit: it would be better avoiding over complicated solutions like ncurses (ncurses doesn't know where's the cursor directly: it computes its position).
Edit 2: I found a way to do it, but it works only in non-graphical terminals: https://www.linuxquestions.org/questions/programming-9/get-cursor-position-in-c-947833/
Edit 3: Nice code and it works well, but it uses /dev/vcsaN (same problem of Edit 2): http://dell9.ma.utexas.edu/cgi-bin/man-cgi?vcs+4
Ncurses is a big and powerful library for creating terminal-based text interfaces.
tputs is a simple low-level universal function for manipulating terminal capabilities.
Either one could serve your needs.
You could try using ncurses' getyx().
This solution is not optimal because it refers to /dev/vcsa*. Hope this could help someone else.
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *device = "/dev/vcsa2";
struct {unsigned char lines, cols, x, y;} scrn;
fd = open(device, O_RDWR);
if (fd < 0) {
perror(device);
exit(EXIT_FAILURE);
}
(void) read(fd, &scrn, 4);
printf("%d %d\n", scrn.x, scrn.y);
exit(EXIT_SUCCESS);
}
Generally you are supposed to remember where you've left the cursor.
However, most terminals do respond to DSR; Device Status Request. By sending
CSI 6 n
you'll receive a CPR; cursor position report, in the form of
CSI Pl;Pc R
where Pl and Pc give the cursor line and column number, indexed from 1.