UINPUT device program in C for Ubuntu 14.04 does not work. Why?

617 views Asked by At

I am using Ubuntu 14.04, and I am setting up a virtual keyboard in c, which requires uinput to work.

I had this root privilege problem:

ls -l /dev/uinput 
crw-rw-rw- 1 root root 10, 223 Feb 25 11:11 /dev/uinput

But I solved it by creating a new rule for this. It now prints:

ls -l /dev/uinput
crw-rw---- 1 root uinput 10, 223 Feb  26 21:11 /dev/uinput

This however still doesn't solve my problem and my program still doesn't work, even with sudo.

Here's my code:

int main()
{
int uinp_fd;
int i;

uinp_fd = open("/dev/uinput", O_WRONLY|O_NDELAY);

if(uinp_fd < 0)
{

    printf("Unable to open /dev/uinput\n");
    return -1;
}

else printf("Can open /dev/uinput\n");

/********* Setup input device structure section: ***********/

memset(&uinp,0,sizeof(uinp));

snprintf(uinp.name, UINPUT_MAX_NAME_SIZE, "The C Keyboard");
uinp.id.bustype = BUS_USB;  
uinp.id.version = 1;
uinp.id.vendor = 0x1234;
uinp.id.product = 0xfedc;

write(uinp_fd, &uinp, sizeof(uinp));


/****** Setup the uinput keyboard device section: **********/

ioctl(uinp_fd, UI_SET_EVBIT, EV_KEY);
ioctl(uinp_fd, UI_SET_EVBIT, EV_SYN);
ioctl(uinp_fd, UI_SET_EVBIT, EV_REP);

ioctl(uinp_fd, UI_SET_KEYBIT, KEY_A);

ioctl(uinp_fd, UI_DEV_CREATE, NULL);

if (ioctl(uinp_fd, UI_DEV_CREATE, NULL) < 0)
{
    printf("Unable to create UINPUT device.\n");
    return -1;
}

My source code continues on further from there.

However, the program always prints "Unable to create UINPUT device.".

sudo command to run my program also doesn't work and the same error message is printed. What should I do to get the program to work? Thanks.

1

There are 1 answers

3
kaylum On BEST ANSWER
ioctl(uinp_fd, UI_DEV_CREATE, NULL);

if (ioctl(uinp_fd, UI_DEV_CREATE, NULL) < 0)
{
    printf("Unable to create UINPUT device.\n");
    return -1;
}

You have invoked the UI_DEV_CREATE ioctl twice. The first call will succeed and the second will fail. So just delete the first call.