I've been using the following C code to try to simulate keystrokes on a CentOS 6.0 machine:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#inlcude <linux/input.h>
#include <linux/uinput.h>
#include <sys/time.h>
static int fd = -1;
struct uinput_user_dev uidev;
struct input_event event;
int main()
{
int i;
fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
memset(&uidev, 0, sizeof(uidev));
snrpintf(uidev.name, UINPUT_MAX_NAME_SIZE, "uinput-kbd");
uidev.id.version = 1;
uidev.id.vendor = 0x1;
uidev.id.product = 0x1;
uidev.id.bustype = BUS_USB;
ioctl(fd, UI_SET_EVBIT, EV_KEY);
for(i = 0; i < 256; i++)
{
ioctl(fd, UI_SET_KEYBIT, i);
}
ioctl(fd, UI_SET_EVBIT, EV_SYN);
write(fd, &uidev, sizeof(uidev));
ioctl(fd, UI_DEV_CREATE));
memset(&event, 0, sizeof(event));
gettimeofday(&event.time, NULL);
event.type = EV_KEY;
event.code = KEY_1;
event.value = 1;
write(fd, &event, sizeof(event));
event.type = EV_SYN;
event.code = SYN_REPORT;
event.value = 0;
write(fd, &event, sizeof(event));
memset(&event, 0, sizeof(event));
gettimeofday(&event.time, NULL);
event.type = EV_KEY;
event.code = KEY_1;
event.value = 0;
write(fd, &event, sizeof(event));
event.type = EV_SYN;
event.code = SYN_REPORT;
event.value = 0;
write(fd, &event, sizeof(event));
ioctl(fd, UI_DEV_DESTROY);
close(fd);
return 0;
}
If I'm correct, this code should create a virtual input device on the machine and then press the "1" key on that device. And when I execute the code, it seems to run without any issues (I haven't include the code that checks to make sure the device is being created and the keystrokes are being written, etc, in my example code, because it would have gotten way too long), but I can't see any sign of the actual keystroke.
My impression was that if I run this from a terminal window while logged directly into the machine, I should see a "1" character appear on the terminal window that I'm running it from. And if I log into the machine via ssh and run it that way, the keystroke should register on the machine rather than the ssh session. But I'm not getting anything in either situation.
Am I misunderstanding the purpose of this code? Have I done it wrong? Or is the more that I need to add to properly simulate a keystroke?