Assuming that your keyboard is in /dev/input/event3
, there follows a code capable of "simulating" the typing of the ls -al
command followed by a enter
:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <sys/time.h>
#include <stdint.h>
#define KEYBOARD_DEVICE_PATH "/dev/input/event3"
int simularTecla( uint16_t tecla )
{
int fd = -1;
struct input_event k;
/* Obtem um descritor para o dispositivo (teclado) */
fd = open( KEYBOARD_DEVICE_PATH, O_WRONLY | O_NONBLOCK );
if( fd < 0 )
return -1;
/* Toma controle exclusivo do teclado */
if(ioctl( fd, EVIOCGRAB, 1 ))
return -1;
/* Pressionando Tecla */
k.type = EV_KEY;
k.value = 1;
k.code = tecla;
gettimeofday( &k.time, NULL );
write( fd, &k, sizeof(struct input_event) );
/* Soltando Tecla */
k.type = EV_KEY;
k.value = 0;
k.code = tecla;
gettimeofday( &k.time, NULL );
write( fd, &k, sizeof(struct input_event) );
/* Liberando controle do teclado */
ioctl( fd, EVIOCGRAB, 0 );
/* Fechando descritor para o dispositivo (teclado) */
close(fd);
/* Sucesso*/
return 0;
}
int main( void )
{
/* Sequencia de teclas */
uint16_t teclas[] = { KEY_L, KEY_S, KEY_SPACE, KEY_MINUS, KEY_A, KEY_L, KEY_ENTER };
unsigned int count = sizeof(teclas) / sizeof(teclas[0]);
unsigned int i = 0;
/* Simula sequencia de teclas */
for( i = 0; i < count; i++ )
simularTecla( teclas[i] );
return 0;
}
Compiling:
$ gcc kbdsim.c -o kbdsim
Testing (as root):
# ./kbdsim
ls -al
# ls -al
total 32
drwxr-xr-x 2 root root 4096 Oct 27 02:18 .
drwxrwxrwt. 30 root root 12288 Oct 27 02:18 ..
-rwxr-xr-x 1 root root 8760 Oct 27 02:18 kbdsim
-rw-r--r-- 1 root root 1287 Oct 27 02:18 kbdsim.c
With a minor change in main()
, you can simulate the activation of the A
key once every second for 100 times in a row:
int main( void )
{
for( i = 0; i < 100; i++ )
{
simularTecla( KEY_A );
sleep(1)
}
return 0;
}
Mapping with each key code can be found here .