flat assembler
Message board for the users of flat assembler.

Index > Linux > Implementing getch and kbhit in Linux

Author
Thread Post new topic Reply to topic
System86



Joined: 15 Aug 2007
Posts: 77
System86
How do you perform getch and kbhit under Linux using int 80h? I know that under Windows, you can use _getch and _kbhit functions in msvcrt.dll, and under DOS you can use int 16h to do this. But how is this done under Linux? I tried using IOCTL with KDSKBMODE and set the keyboard to medium-raw mode for getch (then read the keyboard by calling int 80h with the right parameters) and then restored the keyboard mode, but that simply messed up my kbd so I needed to use alt+sysrq+r to get it back to normal mode. Are there any other IOCTL's I can use to enable reading keystrokes?
Post 07 May 2008, 19:46
View user's profile Send private message Reply with quote
Chewy509



Joined: 19 Jun 2003
Posts: 297
Location: Bris-vegas, Australia
Chewy509
getch: do a 1 byte read (sys_read, eax = 3) with the file handle 00h...

(Default handles in Linux:
STDIN = 00h
STDOUT = 01h
STDERR = 02h
)

Here is the asm (for AMD64):
Code:
mov rax,  03;  // Sys_read
mov rbx,  00h;  // Handle
mov rcx,  buffer;  // Location to store your input
mov rdx,  1;  // 1 byte;
syscall
test rax, rax
jz .@f 
movzx rax, byte [buffer]
jmp forward:
.@@:
xor rax, rax
dec rax
forward:

;; rax contains your character, or -1 if EOF.
    


kbhit: There is no native solution, but the following C version does what you are after:

Code:
/* kbhit.h */

#include <sys/select.h>

int kbhit(void)
{
struct timeval tv;
fd_set read_fd;

tv.tv_sec=0;
tv.tv_usec=0;
FD_ZERO(&read_fd);
FD_SET(0,&read_fd);

if(select(1, &read_fd, NULL, NULL, &tv) == -1)
return 0;

if(FD_ISSET(0,&read_fd))
return 1;

return 0;
}
    


Then you can include the above "kbhit.h" and use the kbhit() function.
For example,

Code:
#include <stdio.h>
#include "kbhit.h"

int main()
{
printf("hello\n");
printf("Press any key to continue..\n");
while(!kbhit());
printf("bye bye\n");

return 0;
}    


I'll let you do the translation into asm... (or use gcc to output the resultant asm).[/code]
Post 08 May 2008, 00:20
View user's profile Send private message Visit poster's website Reply with quote
Display posts from previous:
Post new topic Reply to topic

Jump to:  


< Last Thread | Next Thread >
Forum Rules:
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Copyright © 1999-2020, Tomasz Grysztar. Also on YouTube, Twitter.

Website powered by rwasa.