简体   繁体   English

C 非阻塞键盘输入块在运行级别 3 (Linux)

[英]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.我有一段代码读取键盘输入(用于调试目的),在 Ubuntu 18.04 上用 C 实现。 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.当我尝试在运行级别 3 上运行我的应用程序时,它会在尝试读取键盘字符时阻塞。 This behaviour does not occur when I run the application on run level 5.当我在运行级别 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 ;启动应用程序:运行级别 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).运行级别 3: sudo xinit ./app (应用程序中有 GUI 组件,因此 X 服务器必须在运行级别 3 上启动 - 如果有人对此有更多了解就更好了)。

Update: Turns out if you intialise to the current tty device on runlevel 3, it does not work.更新:事实证明,如果您在运行级别 3 上初始化到当前的 tty 设备,则它不起作用。 Initialising to a specific tty device (in this case tty3) resolves the issue.初始化到特定的 tty 设备(在本例中为 tty3)可解决该问题。

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.不太确定为什么会这样(也许运行级别 3 的默认 tty 是 X 窗口?),如果有人能解释为什么会发生这种情况,我们将不胜感激。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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