简体   繁体   中英

open system calls in C on linux

There are probably several problems with the code below. Found it online after searching for a way to get keyboard input in linux. I've verified the correct event for keyboard input. The reason it seems fishy to me is regardless of what i put in the filepath, it always seems to pass the error check (the open call returns something greater than 0). Something is obviously wrong, so suggestions are welcome.

This won't run correctly unless you run the exe as su.

When i want to read in my keystroke, do i just use something like fgets on the file descriptor in an infinite while loop(would that even work)? I want it to be constantly polling for keyboard inputs. Any tips on decoding the inputs from the keyboard event?

Thanks again! This project of mine may be overly ambitious, as it's been a really long time since i've done any coding.

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>

// Edit this line to reflect your filepath

#define FILE_PATH "/dev/input/event4"

int main()
{
    printf("Starting KeyEvent Module\n");

    size_t file; //will change this to int file; to make it possible to be negative
    const char *str = FILE_PATH;

    printf("File Path: %s\n", str);

    error check here
    if((file = open(str, O_RDONLY)) < 0)
    {
        printf("ERROR:File can not open\n");
        exit(0);
    }

    struct input_event event[64];

    size_t reader; 
    reader = read(file, event, sizeof(struct input_event) * 64);

    printf("DO NOT COME HERE...\n");

    close(file);
    return 0;
}

the problem is here:

size_t file;

size_t is unsigned, so it will always be >=0

it should have been:

int file;

the open call returns something greater than 0

open returns int , but you put in in an unsigned variable ( size_t is usually unsigned), so you fail to detect when it is <0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM