Home > OS >  Is there a way to read mouse wheel data inside while loop without locking while loop in ubuntu in C?
Is there a way to read mouse wheel data inside while loop without locking while loop in ubuntu in C?

Time:02-10

Hello the masters of C and C . I am trying to get mouse wheel data in while loop using read function.

I am in Ubuntu 20.04 and using C language.

Here's brief code I did so far. the "read" function keeps blocking the while loop and waits for the input. I want to process the while loop when there is no input.

Is there any way that I could achieve this? or is there any library that I could use of? It doesn't have to be read function if there's any other way.

Thank you all

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <linux/input.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
  int fd;
  struct input_event event_data;

  if ((fd = open("/dev/input/event19", O_RDONLY)) == -1) {  // mice mouse0 event19
    perror("opening device");
    exit(EXIT_FAILURE);
  }

  // wheel data: 8 2  -1 11 2  -120

  while (1) {
    read(fd, &event_data, sizeof(event_data));
    if (((event_data.code == 8) || (event_data.code == 6)) && (event_data.type == 2) &&
        ((event_data.value == 1) || (event_data.value == -1))) {
        printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
            event_data.value);
    } else if (event_data.code != 0) {
        printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
            event_data.value);
    }
    printf("\nCheck while\n");
  }

  return 0;
}

CodePudding user response:

I think we have 2 method:
1st is use multithread : one thread for reading input and another for main logic. ex https://www.geeksforgeeks.org/multithreading-c-2/
2nd use nonblocking flag like this

int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
while (1)
{

    if (-1 != read(fd, &event_data, sizeof(event_data)))
    {
        if (((event_data.code == 8) || (event_data.code == 6)) && (event_data.type == 2) &&
            ((event_data.value == 1) || (event_data.value == -1)))
        {
            printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
                   event_data.value);
        }
        else if (event_data.code != 0)
        {
            printf("- %d %d: Value=%d\n", event_data.code, event_data.type,
                   event_data.value);
        }
    }

    printf("\nCheck while\n");
}

The code snippet above will configure such a descriptor for non-blocking access. If data is not available when you call read, then the system call will fail with a return value of -1 and errno is set to EAGAIN. See the fnctl man pages for more information

refer : Non-blocking call for reading descriptor

  • Related