简体   繁体   中英

C non-blocking keyboard input blocks on run level 3 (Linux)

I have a piece of code that reads in the keyboard input (used for debugging purposes), implemented in C on Ubuntu 18.04. Since other processes have to run on the same thread, it is initialised as non-blocking.

When I try to run my application on run level 3, it blocks when trying to read in a keyboard character. This behaviour does not occur when I run the application on run level 5.

Does anyone have any answer as to why the behaviour is inconsistent between these two run levels?

This is the code (not shown: where the read operation is called by the application's main loop):

#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>


static int fd;

int kbd_initModule()
{
    fd = open("/dev/tty", O_NONBLOCK | O_NOCTTY);

    if(fd < 0)
    {
        ERROR("Unable to open keyboard: %d", fd);
        return fd;
    }
    else
    {
        return 0;
    }
}

int kbd_deinitModule()
{
    close(fd);
    return 0;
}

int kbd_getEvent()
{
    uint8_t buf[1];

    int tmp = read(fd, buf, sizeof(buf));

    if(tmp == -1)
    {
        ERROR("%s", strerror(errno));
        return -1;
    }
    else
    {
        return buf[0];
    }
}

I am available to answer any questions and provide additional details.

Additional details:

  • Launch app: run level 5: sudo ./app ; run level 3: sudo xinit ./app (there are GUI components in the app, so X server must be started on run level 3 - would be good if someone knew more about this).

Update: Turns out if you intialise to the current tty device on runlevel 3, it does not work. Initialising to a specific tty device (in this case tty3) resolves the issue.

Not really sure why this is the case (maybe the default tty on run level 3 is the X window?), would appreciate if someone could explain why this happens.

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